您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Task implements Runnable{
private CyclicBarrier cyclicBarrier;
public Task(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "准备就绪");
cyclicBarrier.await();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "中断了......");
} catch (BrokenBarrierException e) {
System.out.println(Thread.currentThread().getName() + "抛出损坏异常....");
}
}
}
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始......");
CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
@Override
public void run() {
System.out.println("子线程全部就位,开始执行制定任务......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(2000);
System.out.println("主线程执行完毕");
}
}
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始......");
CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){
@Override
public void run() {
System.out.println("子线程全部就位,开始执行制定任务......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(1000);
t1.interrupt();
Thread.sleep(2000);
System.out.println("主线程执行完毕");
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。