【问题标题】:How to execute all the threads stage by stage如何分阶段执行所有线程
【发布时间】:2018-09-07 07:08:26
【问题描述】:

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

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();

    }
}

【问题讨论】:

    标签: java multithreading


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 2022-06-24
      • 2022-01-10
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多