如何逐步执行所有线程

时间:2018-09-07 07:08:27

标签: java multithreading

如果每个任务(线程)有多个阶段。然后如何确保所有任务都执行阶段1,然后执行阶段2,依此类推。例如如何修改下面的代码,使我的输出是: 任务1的第一阶段, Task2的第1阶段, Task3的第1阶段, Task1的第2阶段, Task2的第二阶段, Task3的第二阶段, 等等...

public class Task implements Runnable{
    public String name;
    static Random random = new Random();

    Task(String name){
        this.name=name;
    }

    public static void main(String args[]) {
        ExecutorService ex = Executors.newFixedThreadPool(6);
        ex.submit(new Task("Task 1"));
        ex.submit(new Task("Task 2"));
        ex.submit(new Task("Task 3"));
    }

    public static void getRandomsleep() {
         try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {
                // ...
            }   }

    public void run() {
        System.out.println("thread name" + this.name);
        getRandomsleep();
        System.out.println("stage 1 of " + this.name);
        getRandomsleep();
        System.out.println("stage 2 of " + this.name);
        getRandomsleep();

    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用CyclicBarrier解决此类问题。

public class CyclicBarrierDemo {

  public static void main(String args[]) {
    CyclicBarrier barrier = new CyclicBarrier(3);
    ExecutorService ex = Executors.newFixedThreadPool(3);
    ex.submit(new Task("Task 1", barrier));
    ex.submit(new Task("Task 2", barrier));
    ex.submit(new Task("Task 3", barrier));
  }

  static class Task implements Runnable {
    String name;
    CyclicBarrier barrier;

    Task(String name, CyclicBarrier barrier) {
      this.name = name;
      this.barrier = barrier;
    }

    void doWork() {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        // ...
      }
    }

    public void run() {
      for (int i = 1; i <= 3; i++) {
        System.out.println("stage " + i + " of " + this.name);
        doWork();
        try {
          barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
          return;
        }
      }
    }
  }
}
输出量
stage 1 of Task 1
stage 1 of Task 2
stage 1 of Task 3
stage 2 of Task 1
stage 2 of Task 2
stage 2 of Task 3
stage 3 of Task 3
stage 3 of Task 1
stage 3 of Task 2