线程中断时未抛出InterruptedException

时间:2016-09-23 04:10:19

标签: java multithreading

我创建了两个类,CheckTimer用于在传递0.3秒时中断thread1。我注意到thread.interrupted()已在CheckTimer.run()中执行,但主要功能中的InterruptedException未被抛出,thread1继续运行而没有任何停止,为什么?是不是thread1.interrupted()应该停止thread1

class CheckTimer extends Thread
{

    /** indicate whether the thread should be running */
    private volatile boolean running = true;

    /** Thread that may be interrupted */
    private Thread thread;

    private int duration;
    private int length;

    public CheckTimer(int length, Thread thread)
    {
        this.duration = 0;
        this.thread = thread;
        this.length = length;
    }


    /** Performs timer specific code */
    public void run()
    {
        // Keep looping
        while(running)
        {
            // Put the timer to sleep
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException ioe)
            {
                break;
            }

            // Use 'synchronized' to prevent conflicts
            synchronized ( this )
            {
                // Increment time remaining
                duration += 100;

                // Check to see if the time has been exceeded
                if (duration > length)
                {
                    // Trigger a timeout
                    thread.interrupt();
                    running = false;
                }
            }
        }
    }
}

class Thread1 extends Thread {
    public void run() {
        while(true) {
            System.out.println("thread1 is running...");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Thread thread1 = new Thread1();
        CheckTimer timer = new CheckTimer(300, thread1);

        timer.start();
        thread1.start();

        try {
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

不,现在应该如何运作。

您必须检查Thread1是否被中断,然后自行抛出异常。

例如,Thread.sleep()中使用了例外,它的实现方式与下面的代码类似。

示例:

if (Thread.interrupted()) {
    throw new InterruptedException();
}

有关它的更多信息:Interrupted Exception Article