打印时我得到空的hashmap,在线程之间共享静态volatile变量的最佳方法是什么?
class RunnableDemo implements Runnable {
int i;
RunnableDemo(int i) {
i = i;
}
public void run(){
finResult.put("value"+str(i), 1);
}
public void start () {
System.out.println("Starting " );
if (t == null) {
t = new Thread (this);
t.start ();
}
}
public class TestThread {
public static volatile ConcurrentHashMap<String, Integer> finResult = new ConcurrentHashMap<String, Integer>();
public static void main(String args[]) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
for(int i=0; i < 4; i++){
RunnableDemo task = new RunnableDemo(i);
executor.execute(task);
}
executor.shutdown();
}
System.out.println(TestThread.finResult);
}
System.out.println(TestThread.finResult);
这应该使用线程中的所有值打印finResult。