重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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://cqcxhl.com/article/gjpchg.html
在线咨询
服务热线
服务热线:028-86922220
TOP