我有一个简单的例子。我想做的是将数组列表分为 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 类中使用中断方法,它会停止两个线程,还是会停止找到数字的实例?
顺便说一句,如果您除了中断之外还有其他解决方案,请告诉我
提前致谢
最佳答案
将您在 LinearSearch 类中创建的线程存储在一个数组中,并让您的 Searcher 类可以访问它们。一旦你的 find 设置为 true,就杀死所有线程。另外,在 Searcher 类中为您的线程提供一个唯一的编号作为 ID。
class Searcher extends Thread {
private int f[];
private int lb, ub;
private int x;
private boolean found;
private int id;
Searcher(int f1[], int a, int b, int x, int id) {
f = f1;
lb = a;
ub = b;
this.x = x;
this.id = id;
}
public void run() {
int k = lb;
found = false;
while (k < ub && !found) {
if (f[k] == x){
found = true;
//this.interrupt();
killAllThreads();
}
k++;
}
}
boolean getResult() {
return found;
}
//assuming your class has access to allThreads array somehow. You will have to decide the best way to keep this variable accessible to this class. Handle null pointer exceptions in your run method
private void killAllThreads(){
for(int i=0; i<allThreads.length; i++){
if(allThreads[i].id != this.id){
if(allThreads[i] != null)
allThreads[i] = null;
}
}
}
}
但是,请参阅here如何安全地杀死线程。
关于java - 中断整个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39795554/