给定一组不相等的输入值(某些输入可能比其他输入更容易解决),如何实现多线程方法来查找单个答案(在一个线程中基于一个“正确”输入)
例如,使用多个线程在这些数组中查找并返回给定的字母 (显然实际程序中数据集更大)
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/