我正在研究多线程程序,其中每个线程都计算两个数字的GCD,将数字和GCD存储到TreeMap
中,并在所有线程完成后打印出TreeMap
。我应该使用什么样的方法来确保只有一个线程同时存储数据,以及如何使用最后一个线程在准备好打印时打印TreeMap
?Java中的多线程和同步
for (int i = 0; i < myList.size(); ++i) {
for (int j = i + 1; j < myList.size(); ++j) {
modulus1 = myList.get(i);
modulus2 = myList.get(j);
pool.execute(new ThreadProcessRunnable(modulus1, modulus2, myMap));
}
}
public void run() {
ThreadProcess process = null;
try {
// Only one thread should execute the following code
for (Map.Entry<BigInteger, ArrayList<BigInteger>> entry : myMap.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
} catch (Exception e) {
System.err.println("Exception ERROR");
}
[Synchronize](http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html)访问数据的方法 – paulsm4
看起来您的'for'循环应该只是一个'if'检查? 'List list = myMap.get(FirstModulus); if(list == null){list = new ArrayList (); myMap.put(FirstModulus,list); } list.add(gcd);'(这消除了对'if(myMap.size()> 0){...} else {...}'的需要,并且使它更可读) –
pickypg
有一个看看这样的线程沟通讨论http://stackoverflow.com/questions/12274821/using-a-static-var-in-a-thread-as-communication-among-different-instances – pickypg