使用ThreadLocal时无法获得正确的结果

时间:2013-09-06 05:27:17

标签: java multithreading local

当我运行代码时,我期待结果显示

Thread-0 - hello-0
Thread-1 - hello-1

但是,第一个线程似乎返回null。我在哪里错了?

public class MyThreadLocal extends Thread {

private static final ThreadLocal<String> testId = new InheritableThreadLocal<String>();


public MyThreadLocal(String testId) {
    this.testId.set(testId);
}

public void run() {
    int loop = 10;

    for (int i=0;i<loop;i++) {
        System.out.println(this.getName()+" - "+testId.get());
        try {this.sleep(1000);} catch (InterruptedException e) {}
    }
}

public static void main(String args[]) {
    new MyThreadLocal("hello-0").start();
    try {Thread.sleep(1000);} catch (InterruptedException e) {}
    new MyThreadLocal("hello-1").start();
}
}

输出

Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0

2 个答案:

答案 0 :(得分:0)

new MyThreadLocal(“hello-0”)在启动线程之前设置ThreadLocal,即在主线程中,而不是在hello-0线程中,这就是它的ThredLocal值= null的原因。新的MyThreadLocal(“hello-1”)以相同的方式起作用,输出的差异是因为你使用了InheritableThreadLocal,所以第二个线程从main继承了本地的线程。

答案 1 :(得分:0)

您正在主线程上设置值(在启动其他线程之前),除了它们在Thread-0和Thread-1上可见。

试试这个:

package ro.derbederos.hlfe.impl.util;

public class MyThreadLocal extends Thread {

private static final ThreadLocal<String> testId = new InheritableThreadLocal<String>();

String testIdString;

public MyThreadLocal(String testId) {
this.testIdString = testId;
}

public void run() {
    int loop = 10;
    testId.set(testIdString);


    for (int i=0;i<loop;i++) {
        System.out.println(this.getName()+" - "+testId.get());
        try {this.sleep(1000);} catch (InterruptedException e) {}
    }
}

public static void main(String args[]) {
    new MyThreadLocal("hello-0").start();
    try {Thread.sleep(1000);} catch (InterruptedException e) {}
    new MyThreadLocal("hello-1").start();
}
}