关于多线程种ThreadLocal使用的疑惑,在线等,请各位大虾帮忙指点一下
代码如下:
public class D {
/**
* @param args
*/
private static ThreadLocal<String> threadLocal= new ThreadLocal<String>();
public static void main(String[] args) {
final CountDownLatch countDownLatch = new CountDownLatch(10);
final List<Future<String>> list = new ArrayList<Future<String>>();
for(int i=0;i<10;i++){
final int val = i;
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<String> future = executor.submit(new Callable<String>(){
public String call() throws Exception {
threadLocal.set(val+"00");
try {
String retVal = update(val);
return retVal;
} catch (Exception e) {
e.printStackTrace();
}finally{
countDownLatch.countDown();
}
return "";
}
});
list.add(future);
}
try {
countDownLatch.await();
for(int i=0;i<list.size();i++){
System.out.println(threadLocal.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String update(final int val){
String no = val+"00";
String retVal = val+"update";
return retVal;
}
}
get的时候都是null,没有值....疑惑了。 --------------------编程问答-------------------- System.out.println(threadLocal.get());
这句话的意思是在mian线程中获取。。。你main线程并没有存储过 --------------------编程问答--------------------
+1
线程池的线程和主线程是不同的线程,线程池对ThreadLocal的操作不影响主线程
所以主线程get是没有东西的
补充:Java , Java SE