Understanding phaser in java with an example

前端 未结 3 644
Happy的楠姐
Happy的楠姐 2021-01-06 11:55

I am trying to understand Phaser in java. I wrote an example which is stuck at advance waiting for other parties to arrive.

As far as I understand, phaser is used as

3条回答
  •  粉色の甜心
    2021-01-06 12:35

    Here is working code with no phaser.register():

    import static java.lang.String.*;
    
    import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CompletionService;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorCompletionService;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Phaser;
    import java.util.stream.IntStream;
    
    public class PhaserUsage implements Callable {
    
        private static final int THREAD_POOL_SIZE = 10;
        private Phaser phaser;
    
        private PhaserUsage(Phaser phaser) {
            this.phaser = phaser;
        }
    
        public static void main(String a[]) {
            ExecutorService execService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
            CompletionService completionService = new ExecutorCompletionService<>(execService);
    
            Phaser phaser = new Phaser(1);
            IntStream.range(0, THREAD_POOL_SIZE)
                    .forEach(nbr -> completionService.submit(new PhaserUsage(phaser)));
    
            execService.shutdown();
    
             try {
                 while (!execService.isTerminated()) {
                    String result = completionService.take().get();
                    System.out.println(format("Result is: %s", result));
                 }
              } catch (ExecutionException | InterruptedException e) {
                 e.printStackTrace();
              }
        }
    
        @Override
        public String call() {
            String threadName = Thread.currentThread().getName();
            System.out.println(format("Registering...%s",threadName));
            //phaser.register();
            System.out.println(format("Arrive and await advance...%s",threadName));
            phaser.arriveAndAwaitAdvance(); // await all creation
            int a = 0, b = 1;
            Random random = new Random();
            for (int i = 0; i < random.nextInt(10000000); i++) {
                a = a + b;
                b = a - b;
            }
            System.out.println(format("De-registering...%s",threadName));
            phaser.arriveAndDeregister();
            return format("Thread %s results: a = %s, b = %s", threadName, a, b);
        }
    }
    

提交回复
热议问题