package com.thread;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
/**
* 主线程等待其他线程执行完毕
*/
public class WhileTrueThread{
public static void main(String[] args) throws Exception {
WhileTrueThread.CyclicBarrierTest();
}
/**
* 多个线城同时执行
* CyclicBarrier.await() 达到 parties(本例子用3个线程)个线程后, parties个线程一同执行
* 如果达不到将一直阻塞线程
* @throws InterruptedException
* @throws BrokenBarrierException
*/
public static void CyclicBarrierTest() throws InterruptedException, BrokenBarrierException {
CyclicBarrier cyclicBarrier=new CyclicBarrier(3);
Thread thread1=new Thread(new ThreadClassCyclicBarrier(cyclicBarrier));
Thread thread2=new Thread(new ThreadClassCyclicBarrier(cyclicBarrier));
//Thread thread3=new Thread(new ThreadClassCyclicBarrier(cyclicBarrier));
thread1.start();
thread2.start();
//thread3.start();
//cyclicBarrier.await();
System.out.println("主线程执行完毕");
}
/**
* 主线程等待 多个线城执行完毕
* CountDownLatch.await() CountDownLatch(3)中 3个线程都执行完毕才执行被await阻塞的主线程
* @throws InterruptedException
*/
public static void CountDownLatchTest() throws InterruptedException{
CountDownLatch countDownLatch=new CountDownLatch(3);
Thread thread1=new Thread(new ThreadClassCountDownLatch(countDownLatch));
Thread thread2=new Thread(new ThreadClassCountDownLatch(countDownLatch));
Thread thread3=new Thread(new ThreadClassCountDownLatch(countDownLatch));
thread1.start();
thread2.start();
thread3.start();
countDownLatch.await();
System.out.println("主线程执行完毕");
}
}
class ThreadClassCountDownLatch implements Runnable {
CountDownLatch countDownLatch = null;
public ThreadClassCountDownLatch(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("ThreadClass 开始执行。。。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadClass 执行完毕 " + "Thread:" + Thread.currentThread().getId());
countDownLatch.countDown();
}
}
class ThreadClassCyclicBarrier implements Runnable {
CyclicBarrier cyclicBarrier=null;
public ThreadClassCyclicBarrier(CyclicBarrier cyclicBarrier){
this.cyclicBarrier=cyclicBarrier;
}
@Override
public void run(){
System.out.println("ThreadClass 开始执行。。。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("ThreadClass 执行完毕 "+"Thread:"+Thread.currentThread().getId());
}
}
java多线程,主线程等待其他子线程执行完毕执行和多个线城一同执行
最新推荐文章于 2021-12-08 21:46:31 发布
本文通过实例展示了Java并发编程中CyclicBarrier和CountDownLatch的使用。CyclicBarrier用于让一组线程等待其他线程到达某个屏障点,而CountDownLatch则允许一个线程等待多个线程完成执行。在示例中,主线程会等待多个子线程执行完毕后再继续执行。了解这两个工具可以帮助优化多线程程序的同步控制。
摘要由CSDN通过智能技术生成