目標是創建搜索方法,該方法返回首先在所有搜索線程中找到的針的索引。當其中一個完成時,我需要停止所有線程。當其中一個完成時停止所有線程
邏輯是:有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 –