我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

JAVA多线程CountDownLatch倒计时锁应用

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

创新互联建站主要从事成都网站设计、网站建设、外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务翼城,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792


分享题目:JAVA多线程CountDownLatch倒计时锁应用
URL地址:http://shouzuofang.com/article/jhcpgc.html

其他资讯