java - 线程局部仅初始化为零

标签 java multithreading runnable thread-local

我正在使用以下代码实现一个线程本地示例,我以为我会在输出中获得随机数,但是当调用 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() 返回 01 之间的 double 值,当您将其转换为 int 时,它将产生 0.

关于java - 线程局部仅初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143105/

相关文章:

java - 有没有办法将参数传递给Runnable?

java - 绑定(bind)到线程 [main] 的键 [org.hibernate.internal.SessionFactoryImpl] 没有值

Java Server Client,线程间共享变量

java - System.nanoTime 与 System.currentTimeMillis

java - 谷歌应用引擎: tasks vs threads?

java - 从扩展可运行的类列表中删除项目是否会终止其线程?

java - 读取套接字响应时,线程在几次迭代后 hibernate

java - 不使用系统属性的带 SSL 的 JMX

java - GWT:如何在两个模块之间共享java对象(即:EventBus)

java - 使用可运行类