您好,登錄后才能下訂單哦!
package concurrent;
import java.util.Random;
import java.util.concurrent.*;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* 分配多個線程共同執行某個任務,等待子線程都結束,主線程才結束
*/
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
CountDownLatch countDownLatch = new CountDownLatch(3);
Future<Integer> future1 = executorService.submit(new CallableTask(countDownLatch));
Future<Integer> future2 = executorService.submit(new CallableTask(countDownLatch));
Future<Integer> future3 = executorService.submit(new CallableTask(countDownLatch));
System.out.println(future1.get());
System.out.println(future2.get());
System.out.println(future3.get());
countDownLatch.await();
executorService.shutdown();
}
}
class CallableTask implements Callable<Integer>{
private CountDownLatch countDownLatch;
public CallableTask(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public Integer call() throws Exception {
int count = 0;
final int random = new Random().nextInt(1000);
for (int i=0;i<random;i++){
count ++;
}
countDownLatch.countDown();
return count;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。