I have a simple example for that. What I would like to do is search an arraylist by divinding it to 2 threads. Here is my main code;
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);
}
}
Here is the Searcher class;
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;
}
}
I divided the array by two and let the threads do their works. The problem was, even if one thread find the number, the other thread still continues its search. When I was looking for an answer it online, I found interrupt method for Threads. If I use interrupt method in my Searcher Thread class, it will stop both of the thread or it will stop the instance which finds the number?
By the way, if you have another solution for the problem except interrupting, please tell me
Thanks in advance