有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么ThreadLocal的initialValue不增加我的变量?

我正在学习多线程;我有以下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

有人能解释为什么会这样吗


共 (1) 个答案

  1. # 1 楼答案

    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