java并发包之Phaser的arriveAndAwaitAdvance方法用法实例演示,秒懂
解决方法:
1.线程类
package com.wlg;
import java.util.concurrent.Phaser;
public class MyThread extends Thread {
public Phaser phaserser;
public MyThread( Phaser phaserser) {
this.phaserser = phaserser;
}
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName()+"到达屏障开始等待时间:"+System.currentTimeMillis());
phaserser.arriveAndAwaitAdvance();
System.out.println("线程"+Thread.currentThread().getName()+"通过屏障时间:"+System.currentTimeMillis());
}
}
2.测试方法,给Phaser对象设置2个parties,ABCDE五个线程隔开2秒分别启动
public static void main( String[] args ) throws InterruptedException {
Phaser phaser = new Phaser(2);
MyThread threadA = new MyThread(phaser);
threadA.setName("A");
threadA.start();
Thread.sleep(2000);
MyThread threadB = new MyThread(phaser);
threadB.setName("B");
threadB.start();
Thread.sleep(2000);
MyThread threadC = new MyThread(phaser);
threadC.setName("C");
threadC.start();
Thread.sleep(2000);
MyThread threadD = new MyThread(phaser);
threadD.setName("D");
threadD.start();
Thread.sleep(2000);
MyThread threadE = new MyThread(phaser);
threadE.setName("E");
threadE.start();
}
3.结果打印
线程A到达屏障开始等待时间:1590468768350
线程B到达屏障开始等待时间:1590468770350
线程B通过屏障时间:1590468770350
线程A通过屏障时间:1590468770350
线程C到达屏障开始等待时间:1590468772351
线程D到达屏障开始等待时间:1590468774351
线程D通过屏障时间:1590468774351
线程C通过屏障时间:1590468774351
线程E到达屏障开始等待时间:1590468776351
由此可见线程A执行arriveAndAwaitAdvance方法后进入等待状态,直到线程B也执行arriveAndAwaitAdvance方法后AB两个线程组队一起通过屏障继续执行,接下来CD也和AB线程一样组队才可以穿过屏障,而E线程没人和他组队执行了arriveAndAwaitAdvance方法后永久进入了漫长的等待中。