【问题标题】:Why initialValue of ThreadLocal doesn't increment my variables?为什么 ThreadLocal 的 initialValue 不会增加我的变量?
【发布时间】: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


    【解决方案1】:

    我想要给每个线程一个我在初始化时发现的 ID id 在线程构造函数中,该值始终为 0(通常 initialValue 应该增加 nextID)

    所以在 MyThread1 类构造函数中你可以这样做:

    public MyThread1(String name) {
        tID = new ThreadID();
        myid = tID.get();
    }
    

    在这种情况下,实际调用 tID.get(); 的线程是 main 线程,,即从主类调用这些构造函数的线程:

    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,在这种情况下,为 主线程。

    但是当我在 Run 函数中初始化 id 时它可以工作!

    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 的原因。一个新的 ID per 线程首次调用 tID.get()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多