日期:2014-05-20 浏览次数:20844 次
----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)
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();
}
}
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 {