【发布时间】:2017-06-12 02:35:00
【问题描述】:
我想在带有@Test 注释的TestNG 类中运行CompletableFuture。
下面是代码sn -p,recursionFuture方法被main()方法递归调用做某项任务。
现在,如果我将main() 用作public static void main(String[] args)),那么一切都会按预期进行。但是当我将main() 与@Test 注释一起使用时,TestNG 会在两者之间停止执行,并且不会执行整个任务。
我应该怎么做才能让@Test等待recursionFuture完成所有任务?
我必须将CompletableFuture 用于异步任务,并且还需要使用@Test。
任何帮助将不胜感激。谢谢。
//public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException
@Test // --> this logic of recursion with threads is problematic with testNG
public static void main() throws FileNotFoundException, InterruptedException, ExecutionException
{
System.setOut(new PrintStream(new File("/Users/Pankaj/Desktop/Thread")));
Method[] method = ConcurrencyPoC_CompletableFuture.class.getMethods();
for(int i=0; i<method.length; i++)
{
if(method[i].getName().startsWith("task"))
{
TreeMap<Object, Object> m = new TreeMap<>();
m.put(method[i].getName(), method[i]);
m.put("status", new AtomicBoolean(true));
taskmap.put(method[i].getName(), m);
}
}
//submitting tasks
ExecutorService ex = Executors.newCachedThreadPool();
CompletableFuture<?> [] arrayFutures = new CompletableFuture[3];
recursionFuture(ex, arrayFutures);
}
public static String recursionFuture(ExecutorService ex, CompletableFuture<?> [] arrayFutures)
{
try
{
//check if any of submitted future is completed - to be used in case of array
for(CompletableFuture<?> future : arrayFutures)
{
future = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);
//storing future in a final variable for further calculation
final CompletableFuture<?> task = future;
CompletableFuture.anyOf(task).thenRunAsync(() ->
{
try {
//apply recursion only when future's output is not null, otherwise there will be hell lot of futures get created which
//don't do anything just eating up memory and executing the else block of executeTask() method.
// Latest change, as soon as any task is free, create a new array of 1 size to do the next task
if(task.get() != null)
recursionFuture(ex, new CompletableFuture[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
, ex);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return "ALl TASK COMPLETED";
}
【问题讨论】:
-
TestNG 为什么会停止?您有任何堆栈跟踪或错误消息吗?你能把 TestNG 的 versbosity 设置为 10 并分享输出吗?
标签: java multithreading testng