App下載
首頁javaconcurrentJava Thread - 如何使用CyclicBarrier來管理線程的順序

Java Thread - 如何使用CyclicBarrier來管理線程的順序

我們想知道如何使用CyclicBarrier來管理線程的順序。
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Main {
  public static void main(String[] args) {
    List<Task> tasks = new LinkedList<Task>();
    String[] tasksLabels = new String[] { "A", "B", "C" };
    Clock clock = new Clock(tasksLabels.length, new Counter());
    for (String s : tasksLabels) {
      Task task = new Task(s, clock);
      tasks.add(task);
      task.start();
    }
  }
}
class Counter implements Runnable {
  volatile int step = 0;
  @Override
  public void run() {
    step++;
  }

  public int getStep() {
    return step;
  }
}
class Clock extends CyclicBarrier {
  Counter counter;
  public Clock(int parties, Counter counter) {
    super(parties, counter);
    this.counter = counter;
  }
  int getStep() {
    return counter.getStep();
  }
}
class Task extends Thread {
  String name;
  Clock clock;
  boolean running = true;
  Random random = new Random();
  Task(String name, Clock clock) {
    this.clock = clock;
    this.name = name;
  }
  boolean checkStep(int step) {
    return true;
  }
  @Override
  public void run() {
    while (running) {
      try {
        doIt(clock.getStep());
        clock.await();
      } catch (InterruptedException e) {
        running = false;
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        running = false;
        e.printStackTrace();
      }
    }
  }
  public void doIt(int step) throws InterruptedException {
    System.out.println(name + ": step " + step);
    // Simulate a busy task
    Thread.sleep(random.nextInt(1000));
  }
}