java线程等待_Java线程等待值

小编典典

创建一些共享存储来保存x每个线程的值,或者如果足够的话,只存储总和。使用a

CountDownLatch等待线程终止。每个线程完成后都会调用CountDownLatch.countDown(),您的myAlgorithm方法将使用该CountDownLatch.await()方法来等待它们。

编辑: 这是我建议的方法的完整示例。它创建了39个工作线程,每个工作线程都将一个随机数添加到一个共享总数中。当所有工人都完成后,将计算并打印平均值。

import java.util.Random;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.atomic.AtomicInteger;

class Worker implements Runnable {

private final AtomicInteger sum;

private final CountDownLatch latch;

public Worker(AtomicInteger sum, CountDownLatch latch) {

this.sum = sum;

this.latch = latch;

}

@Override

public void run() {

Random random = new Random();

try {

// Sleep a random length of time from 5-10s

Thread.sleep(random.nextInt(5000) + 5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

// Compute x

int x = random.nextInt(500);

// Add to the shared sum

System.out.println("Adding " + x + " to sum");

sum.addAndGet(x);

// This runnable is finished, so count down

latch.countDown();

}

}

class Program {

public static void main(String[] args) {

// There will be 39 workers

final int N = 39;

// Holds the sum of all results from all workers

AtomicInteger sum = new AtomicInteger();

// Tracks how many workers are still working

CountDownLatch latch = new CountDownLatch(N);

System.out.println("Starting " + N + " workers");

for (int i = 0; i < N; i++) {

// Each worker uses the shared atomic sum and countdown latch.

Worker worker = new Worker(sum, latch);

// Start the worker

new Thread(worker).start();

}

try {

// Important: waits for all workers to finish.

latch.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

// Compute the average

double average = (double) sum.get() / (double) N;

System.out.println(" Sum: " + sum.get());

System.out.println("Workers: " + N);

System.out.println("Average: " + average);

}

}

输出应该是这样的:

Starting 39 workers

Adding 94 to sum

Adding 86 to sum

Adding 454 to sum

...

...

...

Adding 358 to sum

Adding 134 to sum

Adding 482 to sum

Sum: 10133

Workers: 39

Average: 259.8205128205128

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

import java.util.Random;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Future;

import java.util.concurrent.ScheduledThreadPoolExecutor;

class Worker implements Callable {

@Override

public Integer call() throws Exception {

Random random = new Random();

// Sleep a random length of time, from 5-10s

Thread.sleep(random.nextInt(5000) + 5000);

// Compute x

int x = random.nextInt(500);

System.out.println("Computed " + x);

return x;

}

}

public class Program {

public static void main(String[] args) {

// Thread pool size

final int POOL_SIZE = 10;

// There will be 39 workers

final int N = 39;

System.out.println("Starting " + N + " workers");

// Create the workers

Collection> workers = new ArrayList>(N);

for (int i = 0; i < N; i++) {

workers.add(new Worker());

}

// Create the executor service

ExecutorService executor = new ScheduledThreadPoolExecutor(POOL_SIZE);

// Execute all the workers, wait for the results

List> results = null;

try {

// Executes all tasks and waits for them to finish

results = executor.invokeAll(workers);

} catch (InterruptedException e) {

e.printStackTrace();

return;

}

// Compute the sum from the results

int sum = 0;

for (Future future : results) {

try {

sum += future.get();

} catch (InterruptedException e) {

e.printStackTrace(); return;

} catch (ExecutionException e) {

e.printStackTrace(); return;

}

}

// Compute the average

double average = (double) sum / (double) N;

System.out.println(" Sum: " + sum);

System.out.println(" Workers: " + N);

System.out.println(" Average: " + average);

}

}

输出应如下所示:

Starting 39 workers

Computed 419

Computed 36

Computed 338

...

...

...

Computed 261

Computed 354

Computed 112

Sum: 9526

Workers: 39

Average: 244.25641025641025

2020-11-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值