前言
记一次小坑,java.lang.IllegalMonitorStateException。
解决
看一下官方说Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.意思就是说用wait和notify的时候没有拥有这个监视器对象,下面是我的代码
package thread;
import java.util.LinkedList;
import java.util.Random;
public class MyBlockingQueue {
private LinkedList<Integer> list = new LinkedList<>();
final static int MAX_SIZE = 10;
public void in(Integer i) throws ill{
synchronized (list) {
while (list.size() == 10) {
try {
System.out.println("队列已满,阻塞");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list.add(i);
list.notifyAll();
System.out.println("已读进值此时队列大小为" + list.size());
}
}
public void out() {
synchronized (list) {
while (list.size() == 0) {
try {
System.out.println("队列已空,阻塞");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove();
list.notifyAll();
System.out.println("已删除值此时队列大小为" + list.size());
}
}
public static void main(String[] args) {
MyBlockingQueue queue = new MyBlockingQueue();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Random r = new Random();
int temp = r.nextInt(100);
if (temp > 70) {
queue.in(2);
} else {
queue.out();
}
}
}).start();
}
}
}
找了又找,才发现原来是wait方法前面没有加list。解决