/**
*
* @author 小y
*/
public class PublicBox {
//生产
private int apple = 0;
public synchronized void incrase() {
while (apple == 5) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
apple++;
System.out.println("生产了:" + apple);
}
//消费
public synchronized void decreace() {
while (apple == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
apple--;
System.out.println("消费了:" + apple);
}
public static void main(String[] args) {
PublicBox box = new PublicBox();
Consumer consumer = new Consumer(box);
Producer producer = new Producer(box);
Thread t1 = new Thread(consumer);
Thread t2 = new Thread(producer);
t1.start();
t2.start();
}
}
class Producer implements Runnable {
private PublicBox box;
public Producer(PublicBox box) {
this.box = box;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("producer:" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
box.incrase();
}
}
}
class Consumer implements Runnable {
private PublicBox box;
Consumer(PublicBox box) {
this.box = box;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("consumer:" + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
box.decreace();
}
}
}