我有一个可运行的列表,它们被发送到移相器执行,但它们没有按照调用顺序执行。例如,如果我向移相器发送两个可运行文件,它应该打印“testing 0 testing 1”,但有时它会打印“testing 1 testing 0”
代码在这里:
package org.rs464;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;
public class Test {
private static Runnable submit(int i) {
return () -> System.out.println("testing " + i);
}
public static void main(String[] args) throws InterruptedException {
final List<Runnable> tasks = new ArrayList<>();
for(int i = 0;i<2;i++)
tasks.add(submit(i));
new Test().runTasks(tasks);
}
void runTasks(List<Runnable> tasks) throws InterruptedException {
final Phaser phaser = new Phaser(1) {
protected boolean onAdvance(int phase, int registeredParties) {
return phase >= 1 || registeredParties == 0;
}
};
for (final Runnable task : tasks) {
phaser.register();
new Thread() {
public void run() {
phaser.arriveAndAwaitAdvance();
task.run();
}
}.start();
}
phaser.arriveAndDeregister();
}
}