import java.io.Serializable;
import java.util.concurrent.*;
//public class TestBean {
public class TestBean implements Serializable {
private static final long serialVersionUID = -4790447967459397065L;
private Object name;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public Object getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestBean{" +
"name='" + name + '\'' +
'}';
}
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
CountDownLatch countDownLatch = new CountDownLatch(2);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 2; i++) {
executorService.execute(new WorkerCountDownLatch(countDownLatch, i));
}
countDownLatch.await();
System.out.println("count down main: " + System.currentTimeMillis());
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
for (int i = 0; i < 2; i++) {
executorService.execute(new WorkerCyclicBarrier(cyclicBarrier, i));
}
cyclicBarrier.await();
System.out.println("cyclic barrier main: " + System.currentTimeMillis());
}
static class WorkerCountDownLatch implements Runnable {
private CountDownLatch countDownLatch;
private int i = 1;
public WorkerCountDownLatch(CountDownLatch countDownLatch, int i) {
this.countDownLatch = countDownLatch;
this.i = i;
}
@Override
public void run() {
try {
Thread.sleep(i * 10 * 1000);
System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class WorkerCyclicBarrier implements Runnable {
private CyclicBarrier cyclicBarrier ;
private int i = 1;
public WorkerCyclicBarrier( CyclicBarrier cyclicBarrier , int i) {
this.cyclicBarrier =cyclicBarrier;
this.i = i;
}
@Override
public void run() {
try {
Thread.sleep(i * 10 * 1000);
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
countDownLatch和CyclicBarrier使用示例
最新推荐文章于 2021-10-29 10:39:08 发布