gpt4 book ai didi

java - Java 中的多线程控制

转载 作者:行者123 更新时间:2023-12-01 18:45:14 25 4
gpt4 key购买 nike

我有一个“可运行”线程,它正在启动几个“可调用”线程,并且我想在上述所有线程完成其工作时显示结果。

最好的方法是什么?

我的代码如下

Connector.java(启动可运行线程)

  public class Connector {
private static void anyFileConnector() {
// Starting searching Thread
ExecutorService executor = Executors.newFixedThreadPool(100);
executor.submit(traverse, executor);
//HERE I WANT MY ALL SEARCH RESULTS/OUTPUT : CURRENTLY IT IS STARTING OTHER THREADS AND NOT SHOWING ME ANY RESULTS BECAUSE NONE OF THEM WAS FINISHED.(IN CONSOLE, I WAS ABLE TO SEE RESULTS FROM ALL THE THREADS
setSearchResult(traverse.getResult());

executor.shutdown();
}
}

Traverse.java(可运行线程)我正在使用 ExecutorCompletionService 来处理它......但它没有产生任何区别。 :(

public class Traverse implements Runnable {
public void run() {

ExecutorService executor = Executors.newFixedThreadPool(100);
ExecutorCompletionService<List<ResultBean>> taskCompletionService =
new ExecutorCompletionService<List<ResultBean>>(executor);
try (DirectoryStream<Path> stream = Files
.newDirectoryStream(dir)) {
Search newSearch = new Search();
taskCompletionService.submit(newSearch);
}
list.addAll(taskCompletionService.take().get());
}
}

Search.java(可调用线程)

public class Search implements Callable<List<ResultBean>> {
public List<ResultBean> call() {
synchronized (Search.class) {
// It will return results
return this.search();
}
}

}

最佳答案

选择CyclicBarrier,您将能够实现这一目标。一旦所有线程完成其工作,循环屏障就会执行任务,您可以在此处打印结果。

检查CyclicBarrier的工作情况:http://javarevisited.blogspot.com/2012/07/cyclicbarrier-example-java-5-concurrency-tutorial.html

关于java - Java 中的多线程控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043538/

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