大橙子网站建设,新征程启航

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

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