我有这段代码,它所做的就是等待所有任务都完成,然后才向小部件返回值。WorkerThread是一个可运行程序,需要在下一个循环之前完成。
final ScheduledExecutorService ecs = Executors.newScheduledThreadPool(size2/2);
while(size2>1) {
for (int i = 0; i < size2/2; i++) {
Runnable worker = null;
try {
worker = new WorkerThread(players.take(), players.take() ,area,players);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
ecs.submit(worker);
}
area.append("nn next Round");
size2=size2/2;
}
因此,在这种情况下,我需要做的是完成8个任务,获得它们附加到小部件中的值,然后等待2秒,然后用4个任务继续循环。
您可以使用Phaser
。
Phaser phaser = new Phaser(1); // Create Phaser instance
final ScheduledExecutorService ecs = Executors.newScheduledThreadPool(size2/2);
while(size2>1) {
for (int i = 0; i < size2/2; i++) {
Runnable worker = null;
try {
worker = new WorkerThread(players.take(), players.take() ,area,players);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
phaser.register(); // Register a party
ecs.submit(worker);
}
phaser.arriveAndAwaitAdvance(); // Wait for completion of all tasks
area.append("nn next Round");
size2=size2/2;
}
这是您的消费者。
public class WorkerThread {
public WorkerThread(Phaser phaser) {
this.phaser = phaser;
}
public void run() {
processThings();
phaser.arriveAndDeregister(); // Deregister a party
}
}