Skip to content

Instantly share code, notes, and snippets.

@ellios
Created August 15, 2012 17:31
Show Gist options
  • Save ellios/3361796 to your computer and use it in GitHub Desktop.
Save ellios/3361796 to your computer and use it in GitHub Desktop.
CyclicBarrier和CoundDownLatch简单示例
package me.ellios.concurrency;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
public class BarrierDemo {
private static final int BATCH_SIZE = 10;
private final CyclicBarrier barrier;
private int batchNumber = 1;
private static CountDownLatch latch = new CountDownLatch(BATCH_SIZE);
public BarrierDemo(int batchCount) {
barrier = new CyclicBarrier(batchCount, new Runnable() {
@Override
public void run() {
System.out.println();
System.out.println("******************" + BarrierDemo.this.batchNumber++ + "***********************");
}
});
}
public void doWork(final Runnable work) {
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.print(barrier.await() + ",");
} catch (InterruptedException e) {
} catch (BrokenBarrierException e) {
}
latch.countDown();
work.run();
}
}).start();
}
public static void main(String[] args) throws InterruptedException {
BarrierDemo demo = new BarrierDemo(BATCH_SIZE);
for (int i = 0; i < 100; i++) {
demo.doWork(new Runnable() {
public void run() {
//do something
}
});
if((i + 1)%BATCH_SIZE == 0){
latch.await();
latch = new CountDownLatch(BATCH_SIZE);
}
}
System.out.println();
System.out.println("******************************************");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment