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();
}
}
CountDownLatch 线程等待实例
最新推荐文章于 2020-09-14 10:59:49 发布