gpt4 book ai didi

Java多线程使线程以与它们开始但同时运行的顺序相同的顺序结束

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:51 24 4
gpt4 key购买 nike

我必须编写一个程序来搜索文件中的一堆行并尝试找到给定的子字符串。如果找到它,它会打印出该行。我读取的每一行都创建为一个线程,每个线程搜索文件的一行。到目前为止这不是问题。我需要程序做的是以创建线程的相同顺序打印最终结果(文本行)。 IE。线程 6 不应在线程 2 之前打印。线程同时运行很好,只需要维护打印顺序即可。我不能使用 join 方法,因为我不希望下一个在开始之前等待另一个完全完成,我确实希望它们同时运行。这样做有什么建议吗?此外,该文件可以有任意数量的行,所以我不能硬编码线程数。

线程应该自己打印。主体不进行打印。

最佳答案

首先,线程应用程序的顺序很难定义。看这里:unwanted output in multithreading

如果您希望以特定顺序输出,那么您可能应该使用 ExecutorService这将返回 Future .您提交 Callable<String>返回结果的服务类。提交返回 Future<String> .然后您可以调用 get()来自 Future按照您向服务提交作业的相同顺序。

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// define your jobs somehow as a Callable that returns the line (prolly a string)
List<Future<String>> futures = threadPool.invokeAll(jobsToDo);
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// now we can go through the futures and get the results in order
for (Future<String> future : futures) {
// this returns the results from the `call()` in order or it throws
String resultFromCall = future.get();
}

你的工作Callable类看起来像:

public class MyCallable implements Callable<String> {
private String input;
public MyCallable(String input) {
this.input = input;
}
public String call() {
// search the input string
String result = search(input);
return result;
}
}

关于Java多线程使线程以与它们开始但同时运行的顺序相同的顺序结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18926238/

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