CyclicBarrier 类

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
	final List<StepRunner> srs = new ArrayList<StepRunner>();

	public static void main(String args[]) {
		final ExecutorService es = Executors.newCachedThreadPool();
		final CyclicBarrierTest test = new CyclicBarrierTest();
		CyclicBarrier cb = new CyclicBarrier(5, new Runnable() {

			@Override
			public void run() {
				System.out.println("Go on steps");
				for (StepRunner sr : test.srs) {
					if (sr.getStrides() == 3) {
						System.out.println(sr + " End First!");
						es.shutdownNow();
						return;
					}
				}
			}
		});
		String[] steps = { "Step", "Step", "Step" };
		for (int i = 0; i < 5; i++) {
			StepRunner sr = new StepRunner(i, steps, cb);
			test.srs.add(sr);
			es.execute(sr);
		}

	}

}

class StepRunner implements Runnable {

	private static String[] steps;
	private static CyclicBarrier cb;
	private int strides = 0;
    private int id = -1;
	public StepRunner(int id, String[] steps, CyclicBarrier cb) {
		this.steps = steps;
		this.cb = cb;
		this.id = id;
	}

	public String toString(){
		return "Runner id " + id;
	}
	public synchronized int getStrides() {
		return strides;
	}

	@Override
	public void run() {
		try {
			int i = 0;
			while (!Thread.interrupted()) {
				for (String step : steps) {
					synchronized (this) {
						strides += 1; // Produces 0, 1 or 2
					}
					System.out.println(this + " "+ step + strides + " done!");
					cb.await();
				}
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}


你可能感兴趣的:(CyclicBarrier 类)