标签:barrier sleep 代码 变量 调用 ima nba get imp
CyclicBarrier-循环栅栏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("主线程执行完毕");
}
}
标签:barrier sleep 代码 变量 调用 ima nba get imp
原文地址:https://blog.51cto.com/janephp/2404678