给定一个具有初始化 Phaser 的 main 方法的类,并创建(比如说)3 个线程来计算同一个 Phaser 上的阶段。
public class PhaserDemo2 implements Runnable {
private static Phaser CLASS_PHASER;
private static int COUNTER;
public static void main(String[] args) {
COUNTER = 5;
// create a Phaser and register main Thread
CLASS_PHASER = new Phaser(1);
System.out.println(Integer.MIN_VALUE);
System.out.println("Phase value:" + CLASS_PHASER.getPhase() + ", Registered Parties:"
+ CLASS_PHASER.getRegisteredParties() + ", and Counter:" + COUNTER);
// create 3 Threads
new Thread(new PhaserDemo2()).start();
new Thread(new PhaserDemo2()).start();
new Thread(new PhaserDemo2()).start();
// de-register main Thread
CLASS_PHASER.arriveAndDeregister();
}
@Override
public void run() {
// register the current Thread with Phaser
CLASS_PHASER.register();
// print details
System.out.println("Phase value:" + CLASS_PHASER.getPhase() + ", Registered Parties:"
+ CLASS_PHASER.getRegisteredParties() + ", and Counter:" + COUNTER);
// wait till other Threads have printed as well
CLASS_PHASER.arriveAndAwaitAdvance();
// de-register this Thread
CLASS_PHASER.arriveAndDeregister();
}
}
该代码适用于大多数执行,并产生如下输出,
-2147483648
Phase value:0, Registered Parties:1, and Counter:5
Phase value:0, Registered Parties:2, and Counter:5
Phase value:1, Registered Parties:2, and Counter:5
Phase value:1, Registered Parties:3, and Counter:5
-2147483648
Phase value:0, Registered Parties:1, and Counter:5
Phase value:0, Registered Parties:2, and Counter:5
Phase value:0, Registered Parties:3, and Counter:5
Phase value:0, Registered Parties:3, and Counter:5
但是对于一些奇怪的执行,它会产生如下输出
-2147483648
Phase value:0, Registered Parties:1, and Counter:5
Phase value:0, Registered Parties:2, and Counter:5
Phase value:0, Registered Parties:3, and Counter:5
Phase value:-2147483646, Registered Parties:0, and Counter:5
-2147483648
Phase value:0, Registered Parties:1, and Counter:5
Phase value:0, Registered Parties:2, and Counter:5
Phase value:-2147483646, Registered Parties:0, and Counter:5
Phase value:-2147483646, Registered Parties:0, and Counter:5
-2147483648
Phase value:0, Registered Parties:1, and Counter:5
Phase value:-2147483647, Registered Parties:0, and Counter:5
Phase value:-2147483647, Registered Parties:0, and Counter:5
Phase value:-2147483647, Registered Parties:0, and Counter:5
我不确定这是否可以成功复制,因为这种情况很少发生。否则想知道是什么错误导致了这种情况。
声明: Phaser 的初学者