CountDownLatch 线程等待实例

package com.sgcc.test;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class test {
	
	public static void main1(String[] args) {
		ThreadPoolExecutor poolExe = new ThreadPoolExecutor(100, 1000, 1, TimeUnit.SECONDS,
			    new LinkedBlockingDeque<Runnable>(100));
		// 考试开始铃声响起,考试开始
		final CountDownLatch examBegin = new CountDownLatch(1);
		// 单个考生,考试结束交卷
		final CountDownLatch student = new CountDownLatch(9);
 
		// 一个考场10位考生
		for (int i = 0; i < 10; i++) {
			Runnable runnable = new Runnable() {
				public void run() {
					try {
						System.out.println("考生" + Thread.currentThread().getName() + "在等待考试开始的铃声响起");
						examBegin.await();
						System.out.println("考生听到铃声" + Thread.currentThread().getName() + "开始答题");
						long time = (long) (Math.random() * 100);
						Thread.sleep(time);//答题过程,真正的业务逻辑处理部分
						System.out.println("考生" + Thread.currentThread().getName() + "交卷,答题耗时:"+time);
						student.countDown();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			poolExe.execute(runnable); // 运动员开始任务
		}
 
		try {
			// 答题时间
			Thread.sleep((long) (Math.random() * 10000));
			System.out.println("考场" + Thread.currentThread().getName() + "开始铃声即将响起");
			examBegin.countDown(); // 命令计数器置为0
			System.out.println("考场" + Thread.currentThread().getName() + "考试开始铃声响起");
			student.await(); // 所有考生交卷
			System.out.println("考场" + Thread.currentThread().getName() + "考试结束");
		} catch (Exception e) {
			e.printStackTrace();
		}
		poolExe.shutdown();
 
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值