我提交了許多在多線程上運行的工人。如果有正在運行的員工返回虛假值,我們停止或不提交其他員工。以下是我的示例課程。我應該在TODO部分做什麼?請在這個問題上給我一些建議。每當工人返回虛假值時停止其他工人
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
public class CompletionServiceTest
{
public static void main(final String[] args)
{
ExecutorService cs = Executors.newFixedThreadPool(1);
Collection<Worker> tasks = new ArrayList<Worker>(10);
for(int i=0;i<10;i++) {
tasks.add(new Worker(i+1));
}
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(tasks.size());
try
{
for (Callable task : tasks)
{
futures.add(cs.submit(task));
}
// TODO
// Check if any false value is returned
// Then stop all running tasks, no need to run other tasks anymore
}
finally
{
//Cancel by interrupting any existing tasks currently running in Executor Service
for (Future<Boolean> f : futures)
{
f.cancel(true);
}
}
System.out.println(new Date()+":Done");
}
}
class Worker implements Callable<Boolean>
{
private int number;
public Worker(int number)
{
this.number=number;
}
public Boolean call()
throws InterruptedException
{
try
{
Thread.sleep(50000);
if(number % 4 == 0) {
return false;
} else {
Thread.sleep(500000);
}
}
catch(InterruptedException ie)
{
System.out.println("Worker Interuppted");
throw ie;
}
return true;
}
}
你研究過例如在'ExecutorCompletionService'的javadoc中?這幾乎是你所需要的。 –
我會試試這個。感謝您的幫助,marko :) :) – Barcelona