温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA多线程Callable应用

发布时间:2020-07-29 07:00:26 来源:网络 阅读:949 作者:恋上程序员 栏目:编程语言
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;
    }
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI