一段wait/notify的代码,有时运行成功,有时异常,请教
package com.rzp.wxmp;
public class TestThread {
static volatile Integer sumSize = 0;
static Integer currentSize = 0;
public static void main(String[] args) {
Producer p = new Producer();
p.setDaemon(true);
Customer c = new Customer();
c.setDaemon(true);
p.start();
c.start();
while (sumSize < 20) {
}
}
static class Producer extends Thread {
public Producer() {
super("[Producer made ]");
}
@Override
public void run() {
made();
}
private void made() {
while (sumSize < 20) {
synchronized (currentSize) {
if (currentSize < 1) {
currentSize.notify();
System.out.println(Thread.currentThread().getName() + " made ,currentSize " + currentSize + " sumSize " + sumSize);
sumSize++;
currentSize++;
} else {
try {
currentSize.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
System.out.println(Thread.currentThread().getName() + "I`m made end ");
}
}
static class Customer extends Thread {
int eatSize = 0;
public Customer() {
super("[Customer eat ]");
}
@Override
public void run() {
eat();
}
private void eat() {
while (eatSize < 20) {
synchronized (currentSize) {
if (currentSize > 0) {
currentSize.notify();
System.out.println(Thread.currentThread().getName() + " eat " + eatSize);
currentSize--;
eatSize++;
} else {
try {
currentSize.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
System.out.println(Thread.currentThread().getName() + "I`m eat end");
}
}
} ```
异常信息
``` java
[Producer made ] made ,currentSize 0 sumSize 0
Exception in thread "[Customer eat ]" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.rzp.wxmp.TestThread$Customer.eat(TestThread.java:75)
at com.rzp.wxmp.TestThread$Customer.run(TestThread.java:67)
```
因为你用currentSize作为锁对象 而你的currentSize在变啊 所以currentSize对应的锁肯定也变啊,所以会抛出该异常
产生该异常的原因是不具备对象锁的情况下调用notify,notifyAll或者wait方法
你随便声明一个不变的object或者Integer也行,作为锁对象,取代现在的currentSize,肯定就没有那个异常了