[英]Multiple threads and Synchronization in Java
I'm working on a multithreaded program where each thread calculates the GCD for two numbers, stores the numbers and GCD into a TreeMap
, and prints out the TreeMap
after all the threads finish. 我正在开发一个多线程程序,其中每个线程计算两个数字的GCD,将数字和GCD存储到
TreeMap
,并在所有线程完成后打印出TreeMap
。 What kind of method should I use to make sure that only one thread is storing the data at the same time, and how do I use the last thread to print the TreeMap
when it is ready to print? 我应该使用哪种方法来确保只有一个线程同时存储数据,并且在准备好打印时,如何使用最后一个线程来打印
TreeMap
?
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");
}
You must use syncronize(myMap) {...}
block in places where you need to guarantee single thread access to the map. 您必须在需要保证单线程访问地图的地方使用
syncronize(myMap) {...}
块。
As for printing the result by the last thread, you can use a boolean flag as a signal of completeness and check it every time. 至于通过最后一个线程打印结果,您可以使用布尔值标志作为完整性信号,并每次进行检查。 Don't forget to make it
volatile
to let each thread see its value changes. 不要忘记让每个线程看到其值更改都变得
volatile
。
UPD: Brian Goetz "Java Concurrency In Practice" is a strongly recommended reading. UPD: Brian Goetz强烈建议阅读“ Java并发实践”。
//Only one thread should executes the following code
synchronize{
for (Map.Entry<BigInteger, ArrayList<BigInteger>> entry : myMap.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
}
You can use Collections.synchronizedMap to make it thread safe. 您可以使用Collections.synchronizedMap使其成为线程安全的。 And use thread.join to make sure printing is done only when all threads are dead.
并使用thread.join确保仅在所有线程都已死时才完成打印。
Edit: Do the printing in Main thread.
编辑:在主线程中进行打印。 Just before printing, call
join
on all threads. 在打印之前,请在所有线程上调用
join
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.