您的位置:首页 > 其它

控制并发阶段性任务的改变

2016-07-18 00:01 218 查看

控制并发阶段性任务的改变

Phaser 类提供每次phaser改变阶段都会执行的方法。它是 onAdvance() 方法。它接收2个参数:当前阶段数和注册的参与者数;它返回 Boolean 值,如果phaser继续它的执行,则为 false;否则为真,即phaser结束运行并进入 termination 状态。

如果注册参与者为0,此方法的默认的实现值为真,要不然就是false。如果你扩展Phaser类并覆盖此方法,那么你可以修改它的行为。通常,当你要从一个phase到另一个,来执行一些行动时,你会对这么做感兴趣的。

在这个指南,你将学习如何控制phaser的 phase的改变,通过实现自定义版本的 Phaser类并覆盖 onAdvance() 方法来执行一些每个phase 都会改变的行动。你将要实现一个模拟测验,有些学生要完成他们的练习。全部的学生都必须完成同一个练习才能继续下一个练习。

按照这些步骤来实现下面的例子

package com.packtpub.java7.concurrency.chapter3.recipe6.task;

import java.util.Date;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
* Implements a subclass of the Phaser class. Overrides the onAdvance method to
* control the change of phase
*
*/
public class MyPhaser extends Phaser {

/**
* This method is called when the last register thread calls one of the
* advance methods in the actual phase
*
* @param phase
*            Actual phase
* @param registeredParties
*            Number of registered threads
* @return false to advance the phase, true to finish
*/
@Override
protected boolean onAdvance(int phase, int registeredParties) {
switch (phase) {
case 0:
return studentsArrived();
case 1:
return finishFirstExercise();
case 2:
return finishSecondExercise();
case 3:
return finishExam();
default:
return true;
}
}

/**
* This method is called in the change from phase 0 to phase 1
*
* @return false to continue with the execution
*/
private boolean studentsArrived() {
System.out
.printf("Phaser: The exam are going to start. The students are ready.\n");
System.out.printf("Phaser: We have %d students.\n",
getRegisteredParties());
return false;
}

/**
* This method is called in the change from phase 1 to phase 2
*
* @return false to continue with the execution
*/
private boolean finishFirstExercise() {
System.out
.printf("Phaser: All the students has finished the first exercise.\n");
System.out.printf("Phaser: It's turn for the second one.\n");
return false;
}

/**
* This method is called in the change form phase 2 to phase 3
*
* @return false to continue with the execution
*/
private boolean finishSecondExercise() {
System.out
.printf("Phaser: All the students has finished the second exercise.\n");
System.out.printf("Phaser: It's turn for the third one.\n");
return false;
}

/**
* This method is called in the change from phase 3 to phase 4
*
* @return true. There are no more phases
*/
private boolean finishExam() {
System.out.printf("Phaser: All the students has finished the exam.\n");
System.out.printf("Phaser: Thank you for your time.\n");
return true;
}

public static void main(String[] args) {

// Creates the Phaser
MyPhaser phaser = new MyPhaser();

// Creates 5 students and register them in the phaser
Student students[] = new Student[5];
for (int i = 0; i < students.length; i++) {
students[i] = new Student(phaser);
phaser.register();
}

// Create 5 threads for the students and start them
Thread threads[] = new Thread[students.length];
for (int i = 0; i < students.length; i++) {
threads[i] = new Thread(students[i], "Student " + i);
threads[i].start();
}

// Wait for the finalization of the threads
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Check that the Phaser is in the Terminated state
System.out.printf("Main: The phaser has finished: %s.\n",
phaser.isTerminated());

}

}

class Student implements Runnable {

/**
* Phaser to control the execution
*/
private Phaser phaser;

/**
* Constructor of the class. Initialize its objects
*
* @param phaser
*            Phaser to control the execution
*/
public Student(Phaser phaser) {
this.phaser = phaser;
}

/**
* Main method of the student. It arrives to the exam and does three
* exercises. After each exercise, it calls the phaser to wait that all
* the students finishes the same exercise
*/
public void run() {
System.out.printf("%s: Has arrived to do the exam. %s\n", Thread
.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s: Is going to do the first exercise. %s\n",
Thread.currentThread().getName(), new Date());
doExercise1();
System.out.printf("%s: Has done the first exercise. %s\n", Thread
.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s: Is going to do the second exercise. %s\n",
Thread.currentThread().getName(), new Date());
doExercise2();
System.out.printf("%s: Has done the second exercise. %s\n", Thread
.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s: Is going to do the third exercise. %s\n",
Thread.currentThread().getName(), new Date());
doExercise3();
System.out.printf("%s: Has finished the exam. %s\n", Thread
.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
}

/**
* Does an exercise is to wait a random time
*/
private void doExercise1() {
try {
Long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* Does an exercise is wait a random time
*/
private void doExercise2() {
try {
Long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* Does an exercise is wait a random time
*/
private void doExercise3() {
try {
Long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}


结果

Student 0: Has arrived to do the exam. Sun Jul 17 23:58:44 CST 2016

Student 4: Has arrived to do the exam. Sun Jul 17 23:58:44 CST 2016

Student 2: Has arrived to do the exam. Sun Jul 17 23:58:44 CST 2016

Student 1: Has arrived to do the exam. Sun Jul 17 23:58:44 CST 2016

Student 3: Has arrived to do the exam. Sun Jul 17 23:58:44 CST 2016

Phaser: The exam are going to start. The students are ready.

Phaser: We have 5 students.

Student 2: Is going to do the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 3: Is going to do the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 4: Is going to do the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 1: Is going to do the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 0: Is going to do the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 3: Has done the first exercise. Sun Jul 17 23:58:44 CST 2016

Student 2: Has done the first exercise. Sun Jul 17 23:58:47 CST 2016

Student 0: Has done the first exercise. Sun Jul 17 23:58:50 CST 2016

Student 4: Has done the first exercise. Sun Jul 17 23:58:51 CST 2016

Student 1: Has done the first exercise. Sun Jul 17 23:58:52 CST 2016

Phaser: All the students has finished the first exercise.

Phaser: It’s turn for the second one.

Student 2: Is going to do the second exercise. Sun Jul 17 23:58:52 CST 2016

Student 1: Is going to do the second exercise. Sun Jul 17 23:58:52 CST 2016

Student 3: Is going to do the second exercise. Sun Jul 17 23:58:52 CST 2016

Student 4: Is going to do the second exercise. Sun Jul 17 23:58:52 CST 2016

Student 0: Is going to do the second exercise. Sun Jul 17 23:58:52 CST 2016

Student 1: Has done the second exercise. Sun Jul 17 23:58:56 CST 2016

Student 3: Has done the second exercise. Sun Jul 17 23:58:59 CST 2016

Student 2: Has done the second exercise. Sun Jul 17 23:58:59 CST 2016

Student 0: Has done the second exercise. Sun Jul 17 23:58:59 CST 2016

Student 4: Has done the second exercise. Sun Jul 17 23:59:00 CST 2016

Phaser: All the students has finished the second exercise.

Phaser: It’s turn for the third one.

Student 3: Is going to do the third exercise. Sun Jul 17 23:59:00 CST 2016

Student 4: Is going to do the third exercise. Sun Jul 17 23:59:00 CST 2016

Student 1: Is going to do the third exercise. Sun Jul 17 23:59:00 CST 2016

Student 2: Is going to do the third exercise. Sun Jul 17 23:59:00 CST 2016

Student 0: Is going to do the third exercise. Sun Jul 17 23:59:00 CST 2016

Student 0: Has finished the exam. Sun Jul 17 23:59:04 CST 2016

Student 4: Has finished the exam. Sun Jul 17 23:59:06 CST 2016

Student 1: Has finished the exam. Sun Jul 17 23:59:07 CST 2016

Student 2: Has finished the exam. Sun Jul 17 23:59:07 CST 2016

Student 3: Has finished the exam. Sun Jul 17 23:59:08 CST 2016

Phaser: All the students has finished the exam.

Phaser: Thank you for your time.

Main: The phaser has finished: true.

它是怎么工作的…

这个练习模拟了有3个测验的真实测试。全部的学生必须都完成同一个测试才能开始下一个测试。为了实现这个必须使用同步,我们使用了Phaser类,但是你实现了你自己的phaser通过扩展原来的类,并覆盖onAdvance() 方法.

在阶段改变之前和在唤醒 arriveAndAwaitAdvance() 方法中休眠的全部线程们之前,此方法被 phaser 调用。这个方法接收当前阶段数作为参数,0是第一个phase ,还有注册的参与者数。最有用的参数是actual phase。如果你要基于不同的当前阶段执行不同的操作,那么你必须使用选择性结构(if/else 或 switch)来选择你想执行的操作。例子里,我们使用了 switch 结构来为每个phase的改变选择不同的方法。

onAdvance() 方法返回 Boolean 值表明 phaser 终结与否。如果返回 false 值,表示它还没有终结,那么线程将继续执行其他phases。如果phaser 返回真值,那么phaser将叫醒全部待定的线程们,并且转移phaser到terminated 状态,所以之后的任何对phaser的方法的调用都会被立刻返回,还有isTerminated() 方法将返回真值。

在核心类,当你创建 MyPhaser 对象,在phaser中你不用表示参与者的数量。你为每个 Student 对象调用了 register() 方法创建了phaser的参与者的注册。这个调用不会在Student 对象或者执行它的线程与phaser之间这个建立任何关系。 说真的,phaser的参与者数就是个数字而已。phaser与参与者之间没有任何关系。

转自:http://ifeve.com/thread-synchronization-utilities-7/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  phase 并发