Я представляю многих рабочих, работающих на нескольких потоках. Мы останавливаем или не отправляем других работников, если какой-либо работающий работник возвращает ложное значение. Ниже приведен пример моего образца. Что мне делать в части 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;
}
}
Я играл вокруг этого решения, если вы все еще ищете рабочий пример:
class CompletionServiceTest {
public static void main(String... args) throws Exception {
ExecutorService es = newFixedThreadPool(10);
CompletionService<Boolean> cs = new ExecutorCompletionService<Boolean>(es);
for (int i = 1; i <= 10; i++) cs.submit(new Worker(i));
int count = 0;
while (++count <= 10 && cs.take().get());
es.shutdownNow();
}
}
class Worker implements Callable<Boolean> {
private final int number;
public Worker(int number) {
this.number = number;
}
@Override public Boolean call() throws Exception {
try {
Thread.sleep(1000 + number * 100);
if (number % 4 == 0) {
System.out.printf("worker [%d] failed.\n", number);
return false;
}
System.out.printf("worker [%d] done!\n", number);
return true;
} catch (InterruptedException ie) {
System.out.printf("Worker [%d] stopped!\n", number);
throw ie;
}
}
}
Результат выглядит следующим образом:
worker [1] done!
worker [2] done!
worker [3] done!
worker [4] failed.
Worker [9] stopped!
Worker [7] stopped!
Worker [8] stopped!
Worker [5] stopped!
Worker [6] stopped!
Worker [10] stopped!
future.get()
будет ждать завершения первого работника, что не так
ExecutorCompletionService
? Это в значительной степени именно то, что вам нужно.