Java线程池求解单个结果

标签 java multithreading threadpool

给定一组不相等的输入值(某些输入可能比其他输入更容易解决),如何实现多线程方法来查找单个答案(在一个线程中基于一个“正确”输入)

例如,使用多个线程在这些数组中查找并返回给定的字母 (显然实际程序中数据集更大)

Inputs

[A, B, C, D, E, F]
[G, H]
[I, J, K]
[L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

一旦定位到目标元素,就需要将其从线程返回到调用函数(父线程),并且可以杀死所有其他线程

我考虑过的事情:

使用线程池(“常规”线程、执行器线程)来运行并在调用函数中设置返回值(公共(public)变量?)

循环屏障阻塞主线程,直到找到答案

最佳答案

您可以设置一个 AtomicReference,其中包含由其他任务共享和轮询的答案,以查看它们是否应该停止。您还可以使用它来通知()等待线程。

final AtomicReference result = ...
// adds tasks
synchronized(result) {
    while(result.get() == null)
          result.wait();
}

// to check there is no answer. It doesn't have to be synchronized 
// as the value is thread safe.
while(result.get() == null) {


// in the task when a result is found.
synchronized(result) {
    result.set(answer);
    result.notifyAll();
}

我会使用 ExecutorService。

关于Java线程池求解单个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10186886/

相关文章:

multithreading - 如何使用Delphi和OmniThread在后台将文件上传到azure?

java - Tomcat java 应用程序上的线程饥饿 - 所有线程都在等待 c3p0 BasicResourcePool.awaitAvailable

java - 将 AsyncAppender 添加到 log4j.properties

c - 虚假唤醒的返回值是多少?

java - 按键代码列表(InputProcessor)

c++ - 线程可以被重用来运行可变参数函数吗?

c++ - shared_ptr SIGSEGV 中的无序映射

java - 如何将线程名称写入日志而不是 [p : default-threadpool; w: Idle]

java - 在 Android 上使用 Teechart 制作动画

java - GWT RPC 将对象从服务器端传递到客户端问题