有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中断()中的数组多线程

我正在尝试使用两个线程查找元素,一旦第一个线程找到该元素,它将中断另一个线程 我已将阵列分为两部分(0-length/2)&;(长度/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;
    }

}

共 (3) 个答案

  1. # 1 楼答案

    这似乎是运行多个线程来搜索数组的一种非常复杂的方式,而流似乎是为了解决这个确切的问题而构建的

    考虑:

    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"));
    
  2. # 2 楼答案

    当您在Thread上调用interrupt()方法时,您正在向它发送一个优美的信号,外部有人要求它停止。换句话说,JVM只是将“自愿中断”线程中名为interrupted的标志设置为true。可以使用isInterrupted()方法读取的标志值

    然后,由您在任务/线程内部检查interrupted线程是否由另一个线程设置。您可以通过在while循环中舍入任务活动来实现此行为,例如:

    while (!done && !this.isInterrupted()) {
        // Do some cool stuff
    }
    

    希望这有帮助:)

  3. # 3 楼答案

    mTthread1mT1thread2,因此如果oT是要中断的线程,则应设置:

    mT.setoT(thread2); mT1.setoT(thread1);

    而不是

    mT.setoT(thread1); mT1.setoT(thread2);