【发布时间】:2016-03-11 07:19:59
【问题描述】:
我正在尝试使用两个线程来查找元素,一旦第一个线程找到它将中断其他线程的元素 我将数组分成两部分(0-length/2)和(length/2 -n)来搜索它。 但我无法实现以下功能是我的代码。
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;
}
}
【问题讨论】:
-
唯一可以抛出
InterruptedException的地方是Thread.sleep,但是两个线程同时休眠,你会吞下异常...... -
1) 为什么要睡觉。 2) 你从不检查
isInterrupted()标志,那么你为什么认为调用interrupt会做任何事情呢?? -
请检查帮助您解决问题的答案是否正确:)
标签: java arrays multithreading thread-sleep java-threads