在这篇博客中https://www.cnblogs.com/sweet...
看到以下观点
package thread.base.threadloacl;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
*
* @author ZhenWeiLai
*
*/
public class B {
static final InheritableThreadLocal<String> threadParam = new InheritableThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
//固定池内只有存活3个线程
ExecutorService execService = Executors.newFixedThreadPool(3);
//死循环几次才能看出效果
while (true) {
//线程1,里面有两个子线程
Thread t = new Thread(()->{
threadParam.set("abc");
System.out.println("t1:" + threadParam.get());
Thread t2 = new Thread(()->{
System.out.println("t2:" + threadParam.get());
// threadParam.remove();
});
execService.execute(t2);
Thread t3 = new Thread(()->{
System.out.println("t3:" + threadParam.get());
// threadParam.remove();
});
execService.execute(t3);
});
execService.execute(t);
TimeUnit.SECONDS.sleep(1);
//线程4,线程1同级
Thread t4 = new Thread(()-> {
threadParam.set("CBA");
System.out.println("t4:" + threadParam.get());
});
execService.execute(t4);
}
}
}
t1:abc
t2:abc
t3:abc
t4:CBA
t1:abc
t2:abc
t3:abc
t4:CBA
t1:abc
t2:abc
t3:CBA //因复用线程而导致问题
t4:CBA
我想请问,线程复用导致t3输出CBA是怎么样的一个过程?
Ps:在jdk8下已经复现此问题。
2018年1月18日15:04:32 问题补充:
我使用UnSafe
的staticFieldOffset
获取对象的内存地址,四个线程内部分别执行,地址是一致的。
或许是staticFieldOffset
这个方法并不是获取内存地址的?
try {
Field threadParamF = ThreadPool_1.class.getDeclaredField("threadParam");
System.out.println("t1 threadParam location:" + unsafe.staticFieldOffset(threadParamF));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
慕容森
开心每一天1111
素胚勾勒不出你
月关宝盒
幕布斯7119047
慕斯王
相关分类