最后,我将数组分开并对其各个部分求和,最后使用join将所有内容添加到单个变量中。
类代码主要
We recently prevented a sign-in attempt to this device. You indicated this attempt as yours. For your security, we'll continue to show this device in the list for two weeks. You can also review this event in your Notification & alerts page
类代码线程
int partArray = array.length / THREAD;
int first = 0;
AtomicInteger result = new AtomicInteger(0);
Thread[] thr = new Thread[THREAD];
for(i = 0; i < THREAD; ++i) {
thr[i] = new Thread(new ThreadSum(first, first + partArray, array, result));
thr[i].start();
first += partArray;
}
for(i = 0; i < THREAD; ++i) {
thr[i].join();
}
如何在不使用联接的情况下实现此目的? 任何帮助人员。
答案 0 :(得分:0)
以下是使用线程池的代码版本,该线程池从技术上讲满足了不使用join()
的要求:
int partArray = array.length / THREAD;
int first = 0;
AtomicInteger result = new AtomicInteger(0);
ExecutorService threadPool = Executors.newCachedThreadPool();
for(i = 0; i < THREAD; ++i) {
threadPool.execute(new ThreadSum(first, first + partArray, array, result));
first += partArray;
}
threadPool.shutdown();
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
这里有些事情不好:
join()
,因为否则程序执行中没有精确的点可以安全地检索计算出的和并知道并行求和已完成。synchronized
不需要run方法,因为可以并行汇总单个数组块,并且您已经在使用AtomicInteger
进行同步了。答案 1 :(得分:0)
最后,@ Tudor和@JBNizet的所有答案和评论都帮助我解决了这个问题。我使用了CountDownLatch。
CountDownLatch countDownLatch = new CountDownLatch(THREAD);
for(i = 0; i < THREAD; ++i) {
thr[i] = new Thread(new ThreadSum(first, first + partArray, array, result,countDownLatch));
thr[i].start();
first += partArray;
}
countDownLatch.await();
类代码线程
CountDownLatch countDownLatch;
public ThreadSum(int first, int end, int[] array, AtomicInteger result, CountDownLatch countDownLatch) {
this.first = first;
this.end = end;
this.array = array;
this.result = result;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
int sum = 0;
System.out.println(currentThread().getName());
for(int i = first; i < end; ++i) {
sum += array[i];
}
countDownLatch.countDown();
result.getAndAdd(sum);
}