如何在Java中的线程之间共享Hashmap?

时间:2016-10-01 21:58:42

标签: java multithreading java-threads

打印时我得到空的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。

0 个答案:

没有答案