目标是创建搜索方法,该方法返回首先在所有搜索线程中找到的针的索引。当其中一个完成时,我需要停止所有线程。当其中一个完成时停止所有线程
逻辑是:有4个线程。第一个线程首先检查干草堆的%25,第二个线程检查干草堆的%25-%50等等。
只要其中一人打印文字,我就应该停下来,但我总是得到4个输出,因为他们中的4人都发现了大海捞针。但是,我只需要一个输出。
实施例输出:(下面索引)
I found, it is: 622
I found, it is: 4072
I found, it is: 7519
I found, it is: 7264
这里是SearcherThreat类的扩展Thread
public class SearcherThread extends Thread {
// PROPERTIES
private int needle;
private int[] haystack;
private int start, end;
// CONSTRUCTOR
public SearcherThread(int needle, int[] haystack, int start, int end) {
this.needle = needle;
this.haystack = haystack;
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i < end && !isInterrupted(); ++i) {
if (haystack[i] == needle) {
System.out.println("I found, it is: " + i);
for (SearcherThread searcher : InterruptTest.searchers) {
searcher.interrupt();
}
}
}
}
}
这是包含主类和线程
import java.util.ArrayList;
public class InterruptTest {
public static ArrayList<SearcherThread> searchers = new ArrayList<SearcherThread>();
public static void main(String[] args) throws InterruptedException {
int itemCount = 10000;
int[] haystack = new int[itemCount];
int domainSize = 1000;
for (int i = 0; i < itemCount; ++i)
haystack[i] = (int) (Math.random() * domainSize);
int needle = 10;
int numThreads = 4;
int numItemsPerThread = haystack.length/numThreads;
int extraItems = haystack.length - numItemsPerThread * numThreads;
for (int i = 0, start = 0; i < numThreads; ++i) {
int numItems = (i < extraItems) ? (numItemsPerThread + 1) : numItemsPerThread;
searchers.add(new SearcherThread(needle, haystack, start, start + numItems));
start += numItems;
}
for (SearcherThread searcher : searchers)
searcher.start();
}
}
我这样做,但为什么我得到4输出 –
因为您的工作线程不检查,看他们是否中断。 –
我可能在这里找到了答案http://stackoverflow.com/questions/41389714/threading-search-for-a-value-and-stop-all-threads –