/* 多线程经典问题
* 题目:生产者和消费者问题, 类似的火车站卖票问题
* 作者:王小康
* 时间:2013/5/31
*
* 总结:在多线程中往往会遇到死锁的问题,利用互斥锁可以解决该问题,当然还有别的锁。
* sleep()方法在Thread类里,锁定时别的线程不可以访问锁定对象;
* wait()方法在Object类里,锁定时别的线程可以访问锁定对象。 同时wait()方法与notify()是一对的,
* 后者唤醒某一个正在等待的线程。
*/
public class ProducerConsumer {
public static void main(String[] args) {
Basket bask = new Basket();
Producer p = new Producer(bask);
Consumer c = new Consumer(bask);
new Thread(p).start();
new Thread(c).start();
}
}
class Bread { //面包类
int id;
Bread(int id) {
this.id = id;
}
public String toString() {
return String.valueOf(id);
}
}
class Basket { //篮筐类
int index = 0;
Bread[] bread = new Bread[6];
public synchronized void Push(Bread b) {
while(index == bread.length) {
try {
this.wait();
} catch(InterruptedException e) {
e.getStackTrace();
}
}
this.notify();
bread[index] = b;
index++;
}
public synchronized void Pop(Bread b) {
while(index == 0) {
try {
this.wait();
} catch(InterruptedException e) {
e.getStackTrace();
}
}
this.notify();
index--;
bread[index] = b;
}
}
class Producer implements Runnable { //生产者
Basket bask = null;
Producer(Basket bask) {
this.bask = bask;
}
public void run() {
for(int i = 1; i < 10; i++) {
Bread bread = new Bread(i);
bask.Push(bread);
System.out.println("生产了 :" + bread);
}
}
}
class Consumer implements Runnable { //消费者
Basket bask = null;
Consumer(Basket bask) {
this.bask = bask;
}
public void run() {
for(int i = 1; i < 10; i++) {
Bread bread = new Bread(i);
bask.Pop(bread);
System.out.println("吃了 :" + bread);
}
}
}
运行结果: