private Object object = new Object();
private int i = 0;
public Test() {
new Thread(new Runnable() {
public void run() {
synchronized (object) {
while (true) {
if (i >= 10) {
try {
System.out.println("thread 1 wait");
object.wait();
System.out.println("thread 1 end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
System.out.println("+:" + i);
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
synchronized (object) {
while (true) {
if (i <= 0) {
try {
System.out.println("thread 2 wait");
object.wait();
System.out.println("thread 2 end wait");
} catch (InterruptedException e) {
}
}
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i--;
System.out.println("-:" + i);
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).start();
}
public static void main(String[] args) {
new Test();
}
生产一个,通知消费者消费一个,消费一个通知生产者生产一个.
先notify()再进行wait(),另一个线程才会执行。