I am trying to find element using two threads as soon as 1st thread finds the element it will interrupt other thread i have divided the array into 2 parts (0-length/2) & (length/2 -n) to search over it. But I am not able to achieve the functionality below is my code.
public class Interruptt {
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5, 6, 7, 8, 9 };
int data = 3;
MyThread mT = new MyThread(arr, 0, arr.length / 2, data);
Thread thread1 = new Thread(mT);
MyThread mT1 = new MyThread(arr, arr.length / 2 + 1, arr.length, data);
Thread thread2 = new Thread(mT);
mT.setoT(thread2);
mT1.setoT(thread1);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("enddd");
}
System.out.println("Out");
}
}
class MyThread implements Runnable {
int arr[];
int i;
int data;
int end;
Thread oT;
public MyThread(int[] arr, int i, int end, int data) {
this.i = i;
this.arr = arr;
this.end = end;
this.data = data;
}
@Override
public void run() {
for (int j = i; j < end; j++) {
System.out.println(Thread.currentThread());
if (arr[j] == data) {
System.out.println("data found by thread"
+ Thread.currentThread());
oT.interrupt();
break;
}
}
}
public void setoT(Thread oT) {
this.oT = oT;
}
}