gpt4 book ai didi

java - 每当工作人员返回错误值时停止其他工作人员

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:31 25 4
gpt4 key购买 nike

我提交了许多在多线程上运行的工作人员。如果有任何正在运行的工作人员返回错误值,我们将停止或不提交其他工作人员。下面是我的示例类演示。 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!

关于java - 每当工作人员返回错误值时停止其他工作人员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com