add Phaser implementations (#11051)

This commit is contained in:
Kai Yuan 2021-07-21 05:17:19 +02:00 committed by GitHub
parent c2bfff5698
commit b848bfead3
2 changed files with 53 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package com.baeldung.threadsstartatsametime;
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Phaser;
public class ThreadsStartAtSameTime { public class ThreadsStartAtSameTime {
@ -12,6 +13,11 @@ public class ThreadsStartAtSameTime {
Thread.sleep(30); Thread.sleep(30);
usingCyclicBarrier(); usingCyclicBarrier();
Thread.sleep(30);
usingPhaser();
} }
private static void usingCountDownLatch() throws InterruptedException { private static void usingCountDownLatch() throws InterruptedException {
@ -56,4 +62,25 @@ public class ThreadsStartAtSameTime {
barrier.await(); barrier.await();
} }
private static void usingPhaser() throws InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using Phaser <<<");
System.out.println("===============================================");
Phaser phaser = new Phaser();
phaser.register();
WorkerWithPhaser worker1 = new WorkerWithPhaser("Worker with phaser 1", phaser);
WorkerWithPhaser worker2 = new WorkerWithPhaser("Worker with phaser 2", phaser);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the phaser barrier:");
System.out.println("-----------------------------------------------");
phaser.arriveAndAwaitAdvance();
}
} }

View File

@ -0,0 +1,26 @@
package com.baeldung.threadsstartatsametime;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Phaser;
public class WorkerWithPhaser extends Thread {
private Phaser phaser;
public WorkerWithPhaser(String name, Phaser phaser) {
this.phaser = phaser;
phaser.register();
setName(name);
}
@Override public void run() {
try {
System.out.printf("[ %s ] created, blocked by the phaser\n", getName());
phaser.arriveAndAwaitAdvance();
System.out.printf("[ %s ] starts at: %s\n", getName(), Instant.now());
// do actual work here...
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}