gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:45:21 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com