java wait 超时抛出_java – InterruptionException在wait方法期间抛出时间

本文探讨了Java中Object类wait(long timeout)方法的中断行为。通过实例演示了线程在调用wait()前被中断时,仍会抛出InterruptedException的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Object类的JavaDoc中,在方法wait(long timeout)中,如下所述

“If the current thread is interrupted by any thread before or while it is waiting, then an InterruptedException is thrown”

上述陈述中“之前”的含义是什么?在执行obj.wait()之前是指在执行上面定义的任何指令之前吗?

synchronized (obj) {

while ()

obj.wait(timeout);

... // Perform action appropriate to condition

}

解决方法:

what is meant by “before” in the above statement? before executing

obj.wait() means before executing any instruction defined above it?

这意味着如果线程在执行wait()方法调用之前被中断,那么当实际调用wait()时,这仍然会导致抛出InterruptedException.

为了尝试这种情况,我在下面编写了启动线程并中断它的代码.此线程的run()方法循环INTEGER.MAX_VALE-1次并调用wait()方法.当它到达wait()方法的调用时,线程被中断.随后在调用wait()期间,它抛出了InterruptedException.

public class ThreadWaitInterruption {

static Object obj = new Object();

public static void main(String[] args) {

Thread t = new Thread(new Runnable() {

@Override

public void run() {

System.out.println("Started Thread");

for(int i = 0; i < Integer.MAX_VALUE; i++) {

int j = i/2;

}

System.out.println("Loop completed");

synchronized (obj) {

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

});

t.start();

System.out.println("Interrupting");

t.interrupt();

System.out.println("Interuupted");

}

}

示例输出,使用1.8 Java HotSpot(TM)64位进行测试.

Interrupting

Started Thread

Interuupted

Loop completed

java.lang.InterruptedException

at java.lang.Object.wait(Native Method)

at java.lang.Object.wait(Object.java:502)

at com.demo.threads.ThreadWaitInterruption$1.run(ThreadWaitInterruption.java:19)

at java.lang.Thread.run(Thread.java:745)

要么

Started Thread

Interrupting

Interuupted

Loop completed

java.lang.InterruptedException

at java.lang.Object.wait(Native Method)

at java.lang.Object.wait(Object.java:502)

at com.demo.threads.ThreadWaitInterruption$1.run(ThreadWaitInterruption.java:19)

at java.lang.Thread.run(Thread.java:745)

因此,在中断线程上调用wait()方法会导致InterruptedException被抛出,即使线程在调用wait()方法之前被中断也是如此.

注意:由于它是多线程程序,上面的输出顺序是有保证的,我们可能必须运行这个程序,以获得准确的上述输出.

标签:java,multithreading

来源: https://codeday.me/bug/20190628/1312467.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值