多线程控制 countDownLatch、CyclicBarrier、Semaphore 总结
文章目录
countDownLatch
作用:用于控制多线程执行协调,即线程先后依赖的问题。如主线程需要等待多个子线程执行完成后继续执行。
示例代码(代码中关键点注释)
public class CountDownTest {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("start = " + start);
int num = 100;
LinkedBlockingQueue lbq = new LinkedBlockingQueue();
lbq.stream().count();
final CountDownLatch cdl = new CountDownLatch(num);//参数为线程个数
for (int i = 0; i < num; i++) {
new Thread(() -> {
System.out.println("thread:"+num);
cdl.countDown();//此方法是CountDownLatch的线程数-1
}).start();
}
try {
cdl.await();
}catch (InterruptedException e){
e.printStackTrace();
}
// 通过await()调用,保证以下输出是最末尾输出
long end = System.currentTimeMillis();
System.out.println("end = " + end);
System.out.println("use" + (end - start));
}
}CyclicBarrier
作用:控制多个线程统一时间执行
示例代码(代码中关键点注释)
public class CyclicBarrierTest {
public static void main(String[] args) {
int num = 5;
CyclicBarrier cyclicBarrier = new CyclicBarrier(num);
for(int i = 0;i<num;i++){
new Thread(() -> {
try {
Thread.sleep(num*1000);
System.out.println(new Date().getTime());
//以下调用将会使改线程参与到栅栏控制中,等待所有栅栏内线程全部初始化完成一同执行
//预期结果为多个线程输出的时间戳完全一致
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}Semaphore
作用:控制多个线程同时执行的个数。类似工人和操作台,工人数量大于操作台
示例代码(代码中关键点注释)
public class SemaphoreTest {
public static void main(String[] args) {
int num = 3; //可执行线程数(操作台)
int numThread = 20; //能参与的线程数 (工人)
Semaphore semaphore = new Semaphore(num);
for(int i = 0;i<numThread;i++){
int no = i;
new Thread(()->{
try {
semaphore.acquire(); //工人上工,占用一个操作台
System.out.println("工号:"+ no +"的工人在干活");
Thread.sleep(5000);
System.out.println("工号:"+ no +"的工人下班了");
semaphore.release(); //工人下班,释放操作台
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论