thread在非synchronized方法中调用wait方法

thread在非synchronized方法中调用wait方法

一般的,我们在调用wait方法或者是notify方法时,总被要求在synchronized代码块内调用,那么如果不在synchronized代码块执行会有什么样的情况呢?

测试:

public void waitTest() throws InterruptedException {
    this.wait();
}

public void notifyTest() throws InterruptedException {
    this.notify();
}

可以发现:执行上面的其中一个代码段,都会抛出IllegalMonitorStateException异常:

Exception in thread "main" java.lang.IllegalMonitorStateException
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:502)
	at com.java.thread.InterruptThreadTest.waitTest(InterruptThreadTest.java:19)
	at com.java.thread.InterruptThreadTest.main(InterruptThreadTest.java:14)

发布了76 篇原创文章 · 获赞 66 · 访问量 51万+

猜你喜欢

转载自blog.csdn.net/u013887008/article/details/103109940