【发布时间】:2021-01-13 08:41:49
【问题描述】:
我正在学习多线程;我有以下ThreadID 类:
public class ThreadID {
private static volatile int nextID=0;
private static class ThreadLocalID extends ThreadLocal<Integer>{
protected synchronized Integer initialValue(){
return nextID ++;
}
}
private static ThreadLocalID threadID =new ThreadLocalID();
public static int get(){
return threadID.get();
}
public static void set (int index){
threadID.set(index);
}
}
以及以下Thread 类:
class MyThread1 extends Thread {
int x;
public ThreadID tID;
public int myid;
public MyThread1(String name) {
tID = new ThreadID();
myid = tID.get();
}
public void run() {
System.out.println("la thread =" + tID.get() + " myid= " + myid);
try {
this.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("la thread =" + tID.get() + " apres le sommeil ");
}
}
还有我的main班级:
public static void main(String[] args) {
MyThread1 TH[] = new MyThread1[10];
for (int i = 0; i < 10; i++)
TH[i] = new MyThread1("nom" + i);
try {
for (int i = 0; i < 10; i++) TH[i].start();
for (int i = 0; i < 10; i++) TH[i].join();
} catch (InterruptedException e) {
}
}
问题:
我想要的是给每个线程一个ID;我发现当我在线程构造函数中初始化id 时,值总是0(通常initialValue 应该增加nextID)
la thread =1 myid= 0
la thread =3 myid= 0
la thread =2 myid= 0
但是当我在Run 函数中初始化id 时它可以工作!
la thread =1 myid= 1
la thread =3 myid= 3
la thread =2 myid= 2
谁能解释为什么会这样?
【问题讨论】:
标签: java multithreading concurrency parallel-processing java-threads