Java异常之java.lang.IllegalMonitorStateException

Java异常之java.lang.IllegalMonitorStateException

Exception in thread "Thread2" Exception in thread "Thread1" java.lang.IllegalMonitorStateException
	at java.lang.Object.notifyAll(Native Method)
	at Test.V.run(V.java:9)
	at java.lang.Thread.run(Thread.java:748)
java.lang.IllegalMonitorStateException
	at java.lang.Object.notifyAll(Native Method)
	at Test.V.run(V.java:9)
	at java.lang.Thread.run(Thread.java:748)

获取监视器异常
源码如下:

 public class V implements Runnable {
	static int i=0;
	@Override
	public void run() {
		i=0;
		while (i < 100) {
			notifyAll();
			synchronized (this) {
				
				System.out.println(Thread.currentThread().getName());
				
				try {
					wait();
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
				i++;
				System.out.println(i);
			}
		}
		return ;
	}

	public static void main(String[] args) {
		V v = new V();
		Thread t1 = new Thread(v);
		Thread t2 = new Thread(v);
		t1.setName("Thread1");
		t2.setName("Thread2");
		t1.start();
		t2.start();

	}
}

当你的wait和notify(notify)方法没有放在锁之间的时候,会出现的异常。
源码中是这么注释的
在这里插入图片描述
当前的线程不是拥有锁的对象的线程。事实上在调用wait和notify之后,对象就不是同一个对象了,因此在锁外使用会出现该异常

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值