本案例參考至《Java7并發編程實戰手冊》
在java并發編程的過程中,往往會遇到這樣的需求:現在有多個工人,每個工人都制作同一件產品,而且相對于每個工人來說產品的制作工序都是一樣的。每制作完一道工序,產品都需要使用大型機器進行再加工,為了保證經濟效率。現在要求每一道工序都需要所有的工人完成后,將所有的產品送進工廠加工,加工完畢之后再將產品分發給所有的工人進行下一輪的工序。(也就是說,每道工序都必須等待所有的人完成之后,大家才能繼續下面的工作,只要有一個人沒完成都要等到這個人完成之后才能向下執行)
在java中要實現這樣的需求可以使用Phaser并發階段任務執行機制
工人類(表示工人執行工作的各個步驟)
import java.util.Date;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
public class Worker implements Runnable{
private Phaser phaser;
public Worker(Phaser phaser) {
super();
this.phaser = phaser;
}
@Override
public void run() {
//將每個工人到達工廠的信息打印出來
System.out.printf("%s: Has arrived to do the company. %s---------00000000000000000000\n",Thread.currentThread().getName(),new Date());
//等待所有的線程執行到這里,各個線程才會開始向下執行,不過在向下執行之前會執行phaser的onAdvance()方法
phaser.arriveAndAwaitAdvance();
System.out.printf("%s :Is going to do the frist step.%s******************0\n",Thread.currentThread().getName(),new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s: Has done the frist step. %s\n",Thread.currentThread().getName(),new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s :Is going to do the second step.%s---------1111111111111111111\n",Thread.currentThread().getName(),new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s: Has done the second step. %s*****************1\n",Thread.currentThread().getName(),new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s :Is going to do the thrid step.%s---------222222222222222222\n",Thread.currentThread().getName(),new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s: Has done the thrid step. %s******************2\n",Thread.currentThread().getName(),new Date());
phaser.arriveAndAwaitAdvance();
}
}
自定義的MyPhaser類
/**
* MyPhaser:并發階段任務中的階段切換
* @author JM
* @date 2017-2-27 下午9:54:15
* @since JDK 1.7
*/
public class MyPhaser extends Phaser {
/**
* 重寫onAdvance(int x,int y)方法
* 在Phaser類中,onAdvance(int x,int y)方法在Phaser階段改變的時候會自動執行,
* x表示當前的階段數,y表示注冊的參與者數量
* 如果onAdvance(int x,int y)方法返回false表示phaser在繼續執行,返回true表示phaser已經完成執行并且進入了終止態
*/
@Override
public boolean onAdvance(int phase, int registeredParties) {
switch (phase) {
case 0:
return workersArrived();
case 1:
return finishFristExercise();
case 2:
return finishSecondExercise();
case 3:
return finishExam();
default:
return true;
}
}
/**
* workersArrived:返回false,表明phaser已經開始執行
* @author JM
* 2017-2-27 下午9:53:39
* @return
* boolean
*/
private boolean workersArrived(){
System.out.printf("Phaser: The job are going to start. The workers are ready.\n");
//getRegisteredParties()返回的是注冊的線程數
System.out.printf("We have %d workers.\n",getRegisteredParties());
return false;
}
/**
* finishFristExercise:表示完成了第一階段的工序
* @author JM
* 2017-2-27 下午10:08:04
* @return
* boolean
*/
private boolean finishFristJob(){
System.out.printf("Phaser: All the workers have finished the first step.\n");
System.out.printf("Phaser: It's time to second step.\n");
return false;
}
/**
* finishFristExercise:表示完成了第二階段的工序
* @author JM
* 2017-2-27 下午10:08:04
* @return
* boolean
*/
private boolean finishSecondJob(){
System.out.printf("Phaser: All the workers have finished the second step.\n");
System.out.printf("Phaser: It's time to third step.\n");
return false;
}
/**
* finishFristExercise:表示完成了第二階段的工序
* @author JM
* 2017-2-27 下午10:08:04
* @return
* boolean
*/
private boolean finishJob(){
System.out.printf("Phaser: All the workers have finished the job.\n");
System.out.printf("Phaser: Thank you for your time.\n");
return true;
}
}
測試類
import java.util.concurrent.Phaser;
public class Main {
public static void main(String[] args) {
MyPhaser myPhaser = new MyPhaser();
Woker[] workers= new Worker[5];
for (int i = 0; i < workers.length; i++) {
// 創建五個工人對象,并且通過register()方法將他們注冊到phaser。五個線程,phaser的每個階段
// (調用arriveAndAwaitAdvance()方法的地方)都要等待五個線程執行完才能繼續執行下去
students[i] = new Student(myPhaser);
myPhaser.register();
}
Thread threads[] = new Thread[workers.length];
for (int i = 0; i < workers.length; i++) {
threads[i] = new Thread(workers[i], "Workers" + i);
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("Main:The phaser has finished:%s.\n",myPhaser.isTerminated());
}
}
MyPhaser中,重寫了onAdvance(int phase,int registerParties)方法。其中phaser表示當前階段數(每個線程在完成一階段的任務時可以調用arriverAndAwaitAdvance()等待其他所有線程執行完這個階段,然后再繼續執行下去,這樣每一次調用arriverAndAwaitAdvance()方法就會使phaser階段數加一,所有的線程都完成之后并不是立即向下執行,而是先要執行onAdvance,這個就是onAdvance方法的意義)。