温馨提示×

温馨提示×

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

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

JAVA多线程CountDownLatch倒计时锁应用

发布时间:2020-06-21 23:05:04 来源:网络 阅读:506 作者:恋上程序员 栏目:编程语言
package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Auth: zhouhongliang
 * Date:2019/8/1
 * CountDownLatch倒计时锁
 * 阻塞主线程,等子线程全部执行完之后主线程继续执行
 *
 */
public class CountDownLatchDemo {
    public static int count = 0;
    /**
     * 计算1至10000的和
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        //定义一个缓冲线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //定义一个倒计时锁
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        for (int i=1;i<=10000;i++){
            final int index = i;
            //多个线程执行
            executorService.execute(()->{
                synchronized (CountDownLatchDemo.class){
                    try {
                        count += index;
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //计数器减1
                        countDownLatch.countDown();
                    }
                }
            });
        }
        //线程阻塞,知道countDownLatch计数值=0
        countDownLatch.await();
        System.out.println(count);
                //关闭线程池
        executorService.shutdown();
    }
}

输出结果:50005000

向AI问一下细节

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

AI