How to ensure runnables are executed in a sequential order using a phaser

84 Views Asked by At

I have a list of runnables which are being sent to a phaser for execution but they don't execute in the order they are called. For example, if I send two runnables to the phaser, it should print "testing 0 testing 1" but sometimes it prints "testing 1 testing 0"

The code is here:

package org.rs464;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;

public class Test {

    private static Runnable submit(int i) {
        return () -> System.out.println("testing " + i);
    }

    public static void main(String[] args) throws InterruptedException {

        final List<Runnable> tasks = new ArrayList<>();
        for(int i = 0;i<2;i++)
            tasks.add(submit(i));
        new Test().runTasks(tasks);
    }

     void runTasks(List<Runnable> tasks) throws InterruptedException {  

          final Phaser phaser = new Phaser(1) {  
           protected boolean onAdvance(int phase, int registeredParties) {  
            return phase >= 1 || registeredParties == 0;  
           }  
          };  

          for (final Runnable task : tasks) {  
           phaser.register();  
           new Thread() {  
            public void run() {  
              phaser.arriveAndAwaitAdvance();  
              task.run();  
            }  
           }.start();  
          }  

          phaser.arriveAndDeregister();  

         }  
}
0

There are 0 best solutions below