0

我正在开发一个多线程程序,其中每个线程计算两个数字的 GCD,将数字和 GCD 存储到 a中,并在所有线程完成后TreeMap打印出。TreeMap我应该使用什么样的方法来确保只有一个线程同时存储数据,以及如何使用最后一个线程在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");
    }
4

3 回答 3

1

您必须syncronize(myMap) {...}在需要保证单线程访问地图的地方使用块。

至于由最后一个线程打印结果,您可以使用布尔标志作为完整性信号并每次检查它。不要忘记让它volatile让每个线程看到它的值变化。

UPD: Brian Goetz “Java Concurrency In Practice”是强烈推荐的阅读材料。

于 2013-01-17T05:29:21.807 回答
0
          //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());
            }
}
于 2013-01-17T05:25:19.640 回答
0

您可以使用Collections.synchronizedMap使其成为线程安全的。并使用thread.join确保仅在所有线程都死机时才完成打印。

编辑:在主线程中进行打印。就在打印之前,调用join所有线程。

于 2013-01-17T05:54:45.187 回答