0

When I ran the code, I'm expecting the result to show

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

However, the first thread seems to be returning null. Where am I going wrong here?

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();
}
}

output is

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
4

2 回答 2

0

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

于 2013-09-06T05:42:45.287 回答
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();
}
}
于 2013-09-06T05:51:56.833 回答