package producercustomer;
public class Test2 {
public static void main(String[] args) {
Runnable r = new Resource2();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
}
}
class Resource2 implements Runnable {
private int number = 0;
public synchronized void increase() throws Exception {
if(number !=0) {
this.wait();
}
number++;
System.out.println(number);
notify();//唤醒线程
}
public synchronized void decrease() throws Exception {
if(number == 0) {
this.wait();
}
number--;
System.out.println(number);
notify();
}
@Override //重写run方法
public void run() {
while(true) {
try {
if(number % 2 == 0) {
Thread.sleep((long) (Math.random() *1000));
this.increase();
}
else {
this.decrease();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}