java - 为什么这里抛出中断异常...原因?

标签 java multithreading interrupted-exception

public class TwoThreads {
    private static Object resource = new Object();

    private static void delay(long n) {
        try 
        { 
            Thread.sleep(n);
        }
        catch (Exception e)
        { 

            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.print("StartMain ");
        new Thread1().start();
        delay(1000);                       //dealay 1
        Thread t2 = new Thread2();
        t2.start();   
        delay(1000);                      // delay 2    
        t2.interrupt();                   //here its throwing exception
        delay(1000);                      //delay 3
        System.out.print("EndMain ");
    }

    static class Thread1 extends Thread {
        public void run() {
            synchronized (resource) {
                System.out.print("Startl ");
                delay(6000);
                System.out.print("End1 ");
            }
        }
    }

    static class Thread2 extends Thread {
        public void run() {
            synchronized (resource) {
                System.out.print("Start2 ");
                delay(2000);
                System.out.print("End2 ");
            }
        }
    }
}

我只是在这里感到困惑,为什么当 t2 等待获取资源对象的锁定时 t2.interrupt() 不抛出异常,并且 interrupt() 方法可能会抛出安全性那么为什么编译器仍然允许我们执行它而不将其放入 try catch block 。

最佳答案

同步块(synchronized block)不会抛出 InterruptedException,并且在尝试以这种方式获取监视器时中断线程阻塞不会执行任何操作。

如果您想要此功能,您需要使用具有 lockInterruptibly() 的锁。 ,尽管这并不经常使用。

Acquires the lock unless the current thread is interrupted. Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.

If the current thread already holds this lock then the hold count is incremented by one and the method returns immediately.

If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

The lock is acquired by the current thread; or Some other thread interrupts the current thread. If the lock is acquired by the current thread then the lock hold count is set to one.

If the current thread: has its interrupted status set on entry to this method; or is interrupted while acquiring the lock, then InterruptedException is thrown and the current thread's interrupted status is cleared.

关于java - 为什么这里抛出中断异常...原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17985749/

相关文章:

java - 在 Android Fragments 中按下

java - 如何确保客户端-服务器应用程序中的通信安全?

java - super.onCreate(savedInstanceState) 错误

java - 为包装库设计异常类

c++ - 将多个参数传递给 _beginThreadEx

java - 多线程环境下如何解决内存泄漏?

java - 从 future 抛出 InterruptedException

java - 要么重新中断此方法,要么重新抛出声纳中的“InterruptedException 问题”

c - epoll_wait 由于 EINTR 而失败,如何补救?

c++ - 在线程之间重定向标准输入/输出