17
May

Phraser stages

Step 1: thread classes, which creates phraser.arrive… functions
——————————————————————

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

public class PhaserThread1 implements Runnable {

private Phaser p;
private List myList = new ArrayList<>();

PhaserThread1(Phaser p, List l) {
this.p = p;

Iterator itr = l.iterator();
while (itr.hasNext())
myList.add(itr.next());
}

public List getMyList() {
myList.add(99);
return myList;
}

@Override
public void run() {
System.out.println(“Thread 1 arrived”);
p.arriveAndAwaitAdvance();
System.out.println(“Thread 1 completed”);
}

}

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

public class PhaserThread2 implements Runnable {

private Phaser p;
private List myList = new ArrayList<>();

PhaserThread2(Phaser p, List l) {
this.p = p;

Iterator itr = l.iterator();
while (itr.hasNext())
myList.add(itr.next());
}

public List getMyList() {
return myList;
}

@Override
public void run() {
System.out.println(“Thread 2 arrived”);
p.arriveAndAwaitAdvance();
System.out.println(“Thread 2 completed”);
}

}

Step2: Executor which runs above threads
—————————————–
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;

public class Executor {
private static Phaser p = new Phaser(2);
private static List myList = new ArrayList<>();

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

for (int i = 0; i < 10; i++) myList.add(i); PhaserThread1 obj1 = new PhaserThread1(p, myList); PhaserThread2 obj2 = new PhaserThread2(p, myList); System.out.println("Main thread is at phase "+p.getPhase()); Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); t1.start(); t2.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t1.join(); t2.join(); System.out.println("Main thread is at phase "+p.getPhase()); Thread t11 = new Thread(obj1); Thread t21 = new Thread(obj2); t11.start(); t21.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t11.join(); t21.join(); System.out.println("Main thread is at phase "+p.getPhase()); Thread t111 = new Thread(obj1); Thread t211 = new Thread(obj2); t111.start(); t211.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t111.join(); t211.join(); System.out.println("Main thread is at phase "+p.getPhase()); } } Output: ------- Main thread is at phase 0 Thread 1 arrived Thread 2 arrived Thread 1 completed Thread 2 completed Main thread is at phase 1 Thread 2 arrived Thread 1 arrived Thread 1 completed Thread 2 completed Main thread is at phase 2 Thread 2 arrived Thread 1 arrived Thread 1 completed Thread 2 completed Main thread is at phase 3