日期:2014-05-20  浏览次数:20781 次

关于java多线程的一个异常IllegalMonitorStateException
本帖最后由 wave900309 于 2013-03-15 15:33:13 编辑
如果我用Integer的变量count做锁的话就会报异常
----1
++++0
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at net.ken.thread2.AllInOne$Consumer.run(AllInOne.java:50)
at java.lang.Thread.run(Thread.java:722)
++++1
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at net.ken.thread2.AllInOne$Producer.run(AllInOne.java:22)
at java.lang.Thread.run(Thread.java:722)


注意锁是count,同时也做仓库用
package net.ken.thread2;

public class AllInOne {

private static final int MAX_SIZE = 10;
Integer count = 0;
class Producer implements Runnable {

@Override
public void run() {
while (true) {
synchronized (count) {
try {
if (count == MAX_SIZE) {
System.out.println("full, wait!");
count.wait();

} else {
count++;
Thread.sleep(((int) Math.random() + 1) * 1000);
System.out.println("++++" + count);
count.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

}
}

class Consumer implements Runnable {

@Override
public void run() {
while (true) {
synchronized (count) {
try {
if (count == 0) {
System.out.println("empty, wait");
count.wait();
} else {
System.out.println("----" + count);
count--;
Thread.sleep(((int) Math.random() + 1) * 1000);
count.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}

void start() {
Runnable p = new Producer();
Runnable c = new Consumer();
new Thread(p).start();
new Thread(c).start();
}

/**
 * @param args
 */
public static void main(String[] args) {
new AllInOne().start();
}

}



但是如果用LinkedList类型的count做锁就不会报异常(我还试过专门生成一个Object类型的对象专门用来做锁,这样也不会报异常),请问是什么问题呢?
package net.ken.thread2;

import java.util.LinkedList;

public class AllInOne {

private static final int MAX_SIZE = 10;
LinkedList<Object> count = new LinkedList<Object>();

class Producer implements Runnable {

@Override
public void run() {
while (true) {
synchronized (count) {
try {
if (count.size() == MAX_SIZE) {
System.out.println("full, wait!");
count.wait();

} else {