在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