我有一个简单的例子。我想要做的是通过将它排除为2个线程来搜索一个数组列表。这是我的主要代码;中断整体线程
class LinearSearch {
public static void main(String args[]) {
int list[] = new int[1000];
for (int j = 0; j < list.length; j++)
list[j] = (int) (Math.random() * 1000);
for (int y : list)
System.out.print(y + " ");
System.out.println();
System.out.print("Enter number to search for: ");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
Searcher t = new Searcher(list, 0, 500, x);
Searcher t1 = new Searcher(list, 500, 1000, x);
t.start();
t1.start();
try {
t.join();
t1.join();
} catch (InterruptedException e) {
}
boolean found = t.getResult() || t1.getResult();
System.out.println("Found = " + found);
}
}
这是Searcher类;
class Searcher extends Thread {
private int f[];
private int lb, ub;
private int x;
private boolean found;
Searcher(int f1[], int a, int b, int x) {
f = f1;
lb = a;
ub = b;
this.x = x;
}
public void run() {
int k = lb;
found = false;
while (k < ub && !found) {
if (f[k] == x){
found = true;
this.interrupt();
}
k++;
}
}
boolean getResult() {
return found;
}
}
我把数组分成两部分,让线程完成它们的工作。问题是,即使一个线程找到号码,另一个线程仍然继续搜索。当我在网上寻找答案时,我发现线程的中断方法。 如果我在我的Searcher Thread类中使用中断方法,它会停止两个线程,或者它会停止发现该数字的实例?
顺便说一句,如果你有除了中断问题的另一种解决方案,请提前告诉我
感谢
你认为中断当前线程会做什么? –