中断睡眠线程

Don*_* Ch 5 java multithreading interrupt

试图中断正在运行的线程,在本例中为t1,它由线程池中的线程执行.

t2是发送中断的那个.

我无法停止运行t1,t1没有得到InterruptedException.

我错过了什么?

    Executor exec1 = Executors.newFixedThreadPool(1);

    // task to be interrupted
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("starting uninterruptible task 1");
                Thread.sleep(4000);
                System.out.println("stopping uninterruptible task 1");
            } catch (InterruptedException e) {
                assertFalse("This line should never be reached.", true);
                e.printStackTrace();
            }               
        }           
    };
    final Thread t1 = new Thread(runnable);


    // task to send interrupt
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                t1.interrupt();
                System.out.println("task 2 - Trying to stop task 1");
                Thread.sleep(5000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }               
        }           
    };
    Thread t2 = new Thread(runnable2);

    exec1.execute(t1);
            t2.start();
    t2.join();
Run Code Online (Sandbox Code Playgroud)

Beg*_*moT 3

看来您误解了线程和执行器。您为两个可运行对象创建两个线程对象,但仅启动其中一个(t2),t1 传递给 Executor 在其中运行。但执行器不需要提供 Thread——它只需要 Runnable 实现。Executor 本身是一个线程池(通常,但不是必需的),它只是在其中创建(和池化)线程。它认为你的线程就像简单的 Runnable (这是 Thread 实现的)一样。所以你实际上向从未启动的线程发送中断。

如果你真的想让你的代码正常工作,你应该删除 Executor,然后显式启动两个线程。