我有几个任务这样的:如何分配任务CompletableFuture因此多数民众赞成一旦拿起,它不应该再度回升
public static String task1()
public static String task2()
public static String task3()
public static String task4()
public static String task5()
public static String task6()
我想通过并行使用CompletableFuture执行这些任务,但在与执行异步方式:
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> executeTask(), executor);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> executeTask(), executor);
CompletableFuture<Object> future3 = CompletableFuture.supplyAsync(() -> executeTask(), executor);
executeTask()是要被执行以检索任务的方法中,现在的问题是当我开始执行上面的代码然后TASK1()由所有future1拾取,future2和future3以及task2被全部收购,因为所有的期货都在运行以并行方式和异步方式。 我想要的 - 一旦任何未来物件被拾取,就不应该被其他物件拾取。我如何做到这一点。任何帮助,将不胜感激。谢谢。这里有一个地图(静态TreeMap> map = new TreeMap <>();)其中包含方法名称和方法,以Tasks的形式返回,如task1, task2等等。现在我在这里做的是:我迭代地图并找到那个没有关键状态的条目,这意味着这个任务可以被执行并返回,在返回之前,我将状态键放到“再次拿起。现在所有的未来都是以异步的方式运行,这就是为什么所有人都在一起选择task1等等。
public static Object executeTask()
{
Object result = null;
try
{
Method method = null;
for(Entry<String, HashMap<String, Method>> en : map.entrySet())
{
if(!en.getValue().containsKey("status"))
{
System.out.println("Found free task: "+en.getKey().toString());
method = en.getValue().get(en.getKey());
en.getValue().put("status", ConcurrencyPoC_CompletableFuture.class.getMethod("toString"));
break;
}
}
if(method != null)
{
System.out.println("Executing : "+method.getName());
result = (String) method.invoke(new ConcurrencyPoC_CompletableFuture());
}
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
executeTask()的返回需要由期货拾起一个任务,有返回的递归在方法executeTask()中,以便每当应该有一个任务返回,只要有任何。我不知道如何限制这一点。一些更多的信息将是有用的。谢谢。 –
@PankajKatiyar如果你想让任务只执行一次,你应该只返回一次任务。你是说你不能改变代码吗?我不确定什么阻止了你。 –
我已经添加了executeTask的代码,它一直被调用来返回任务,我不知道我可以在那里做些什么改变。你能再次看看它吗, –