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

标签 java multithreading search concurrency

我必须编写一个程序来搜索文件中的一堆行并尝试找到给定的子字符串。如果找到它,它会打印出该行。我读取的每一行都创建为一个线程,每个线程搜索文件的一行。到目前为止这不是问题。我需要程序做的是以创建线程的相同顺序打印最终结果(文本行)。 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/

相关文章:

algorithm - bing背后的技术是什么?它自己的 map-reduce 算法版本还是其他?

java - mySql-java 简单搜索控制台应用程序

android - 如何在 Textview 中搜索单词?

java - 使用 JButton 更改 JFrame 中的背景颜色

java - Java Spring Boot 中的服务器端渲染 React

java - 如何在 min3d Android 中平移放大缩小功能

Java swt - 在缩放和缩放后从图像中获取实际的 x,y 坐标

database - 使用锁插入 B+ 树

c# - Windows Phone 8 线程无效的跨线程访问

java - 如何使用 wait 和 notification JavaFX 暂停线程