我是靠谱客的博主 能干草莓,这篇文章主要介绍多线下,CountDownLatch,Future的使用,现在分享给大家,希望可以做个参考。

在处理业务的时候,往往需要发起多个线程去查询,处理,然后等待所有线程执行完,再进行业务合并处理。
1,CountDownLatch的使用
CountDownLatch更像是一个计数器,可以设置线程数,进行递减。countDownLatch.countDown();线程处理完以后减少,countDownLatch.await();等待所有的线程处理完。举例:

public class CountDownLatchTest {

public static void main(String[] args){
    final CountDownLatch countDownLatch = new CountDownLatch(5);
    for (int i = 0; i < 5; i++) {
        final int no = i;
        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(no);
            }
        }).start();
        countDownLatch.countDown();

    }
    try {
        countDownLatch.await();
        System.out.println("线程执行完了");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

}

2,Future的使用
Future结合Callable的使用,线程可以有返回值。举例:

public class FutureTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
List< Future> futureList = new ArrayList Future();
for (int i = 0; i < 5; i++) {
//FutureTask也可以使用
Future future = threadPool.submit(new Callable() {
@Override
public Integer call() throws Exception {
return new Random().nextInt(10);
}
});
futureList.add(future);
}
for (Future f : futureList) {
try {
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
3.CyclicBarrier比CountDownLatch的使用场景更复杂,自行了解。

最后

以上就是能干草莓最近收集整理的关于多线下,CountDownLatch,Future的使用的全部内容,更多相关多线下,CountDownLatch,Future内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部