我正在使用以下代码实现一个线程本地示例,我以为我会在输出中获得随机数,但是当调用 threadLocal.get()
方法时,我得到的所有数字都是零线程 n 输出,我在这里遗漏了什么吗?这是我的代码和输出,将深深感谢您的帮助。提前致谢。
package concurrency;
public class ThreadLocalExample {
public static void main(String[] args) throws InterruptedException {
SubLocalClass subLocalClass = new SubLocalClass();
for(int i=0;i<10;i++) {
Thread thread = new Thread(subLocalClass);
thread.start();
thread.join();
}
}
}
class SubLocalClass implements Runnable{
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 1000;
}
};
@Override
public void run() {
threadLocal.set((int) Math.random());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+" "+
Thread.currentThread().getName()+" "+threadLocal.get());
}
}
我得到的输出是这样的
12 Thread-0 0
13 Thread-1 0
14 Thread-2 0
15 Thread-3 0
16 Thread-4 0
17 Thread-5 0
18 Thread-6 0
19 Thread-7 0
20 Thread-8 0
21 Thread-9 0
为什么所有线程的threadLocal.get()
的0
,不应该发布随机数吗?
感谢您对此的帮助。
最佳答案
您将本地线程设置为零:
threadLocal.set((int) Math.random());
因为 Math.random()
返回 0
和 1
之间的 double 值,当您将其转换为 int 时,它将产生 0
.
关于java - 线程局部仅初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143105/