成都创新互联网站制作重庆分公司

JAVA多线程Callable应用

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 future1 = executorService.submit(new CallableTask(countDownLatch));
        Future future2 = executorService.submit(new CallableTask(countDownLatch));
        Future 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{
    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

网页名称:JAVA多线程Callable应用
网站地址:http://cxhlcq.com/article/gjpchg.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部