我正在学习多线程;并且我有以下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
但是当我在id
函数中初始化Run
时,它起作用了!la thread =1 myid= 1
la thread =3 myid= 3
la thread =2 myid= 2
谁能解释为什么会这样?
最佳答案
What I want is to give each Thread an ID I found that when I init the id in the thread constructor the value is always 0 (normally the initialValue should increment the nextID)
因此,在
MyThread1
类构造函数中,您可以执行以下操作:public MyThread1(String name) {
tID = new ThreadID();
myid = tID.get();
}
在这种情况下,实际调用tID.get();
的线程是主线程,即从主类调用这些构造函数的线程:MyThread1 TH[] = new MyThread1[10];
for (int i = 0; i < 10; i++)
TH[i] = new MyThread1("nom" + i);
第一次调用tID.get()
将生成一个新的ID
作为0
,因为这是任何线程第一次调用tID.get()
。来自同一线程(即主线程)的下一次调用不会生成新的ID
,而是始终返回相同的ID,在这种情况下,将为主线程返回0
。but when I init the id inside the Run function it works!
在
run
方法内部: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 ");
}
tID.get()
将由不同的线程调用,这就是为什么您获得新的ID。每个线程首次调用tID.get()
时将使用一个新的ID。
关于java - 为什么ThreadLocal的initialValue不会增加我的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65698334/