java中断()中的多线程
我正在尝试使用两个线程查找元素,一旦第一个线程找到该元素,它将中断另一个线程 我将数组分为两部分(0-length/2)和(length/2-n)来搜索它。 但我无法实现下面的功能是我的代码java中断()中的多线程,java,arrays,multithreading,thread-sleep,java-threads,Java,Arrays,Multithreading,Thread Sleep,Java Threads,我正在尝试使用两个线程查找元素,一旦第一个线程找到该元素,它将中断另一个线程 我将数组分为两部分(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; My
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;
}
}
公共类中断{
公共静态void main(字符串[]args){
int[]arr={2,3,4,5,6,7,8,9};
int数据=3;
MyThread mT=新的MyThread(arr,0,arr.length/2,数据);
螺纹1=新螺纹(mT);
MyThread mT1=新的MyThread(arr,arr.length/2+1,arr.length,data);
螺纹2=新螺纹(mT);
塞托山(螺纹2);
mT1.setoT(螺纹1);
thread1.start();
thread2.start();
试一试{
thread1.join();
螺纹2.连接();
}捕捉(中断异常e){
//TODO自动生成的捕捉块
系统输出打印项次(“enddd”);
}
System.out.println(“out”);
}
}
类MyThread实现可运行{
int-arr[];
int i;
int数据;
内端;
螺纹oT;
公共MyThread(int[]arr,int i,int end,int data){
这个。i=i;
this.arr=arr;
this.end=end;
这个数据=数据;
}
@凌驾
公开募捐{
对于(int j=i;j
mT
是thread1
mT1
是thread2
因此,如果oT
是要中断的线程,则应设置:
mT.setoT(螺纹2);
mT1.setoT(螺纹1)代码>
而不是
mT.setoT(螺纹1);
mT1.setoT(螺纹2)代码>当您在线程上调用中断()
方法时,您正在向它发送一个优美的信号,外部有人要求它停止。换句话说,JVM只是将“自愿中断”线程中名为interrupted
的标志设置为true
。可以使用isInterrupted()
方法读取的标志值
然后,由您在任务/线程内部检查中断的线程是否由另一个线程设置。您可以通过在循环中对任务活动进行取整来实现此行为,而循环如下:
while (!done && !this.isInterrupted()) {
// Do some cool stuff
}
希望有帮助:)这似乎是一种非常复杂的运行多线程来搜索数组的方法,而流似乎是为了解决这个确切的问题而构建的
考虑:
int[] arr = {2, 3, 4, 5, 6, 7, 8, 9, 0};
int data = 2;
IntStream.of(arr)
.parallel()
.filter(i -> i == data)
.findAny()
.ifPresent(i -> System.out.println("Found"));
唯一可以抛出InterruptedException
的地方是Thread.sleep
,但是两个线程同时睡眠,您会吞下异常…1)为什么睡眠。2) 你从不检查标志,那么为什么你认为调用中断会有任何作用呢?请检查帮助你解决问题的正确答案:)我猜是Java 8?如果是的话,我想指出这一点是很好的。为什么不是Java8呢?