/*多线程经典问题
* 生产者和消费者:
* 1.生产者边生产,消费者边消费
* 2.仓库满了则暂停生产,仓库空了就暂停消费。
* 【使用wait()方法:使得当前线程立刻停止运行,处于等待状态(WAIT),并将当前线程置入锁对象的等待队列中,直到被通知(notify)或被中断为止。】
* 3.发生生产后,通知对方消费。发生消费后,通知对方生产。
* 【使用:notifyAll()方法;唤醒所有处于等待状态的线程---或者:notify()方法:唤醒处于等待状态的线程】
* */
public class ProducerAndConsumer{
public static void main(String[] args) {
BufferZone bufferZone = new BufferZone();
new Producer(bufferZone).start();
new Consumer(bufferZone).start();
}
}
//生产者
class Producer extends Thread{
BufferZone bufferZone;
public Producer(BufferZone bufferZone){
this.bufferZone = bufferZone;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
bufferZone.push(new Product(i));
System.out.println("生产了第"+(i+1)+"个产品");
}
}
}
//消费者
class Consumer extends Thread{
BufferZone bufferZone;
public Consumer(BufferZone bufferZone){
this.bufferZone = bufferZone;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// try {
// sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
bufferZone.pop();
System.out.println("消费了第"+(i+1)+"个产品");
}
}
}
//产品
class Product{
//产品编号
int id;
public Product(int id) {
this.id = id;
}
}
//缓冲区
class BufferZone{
//可以理解为仓库,设置一个为大小为10的仓库
Product[] storehouse = new Product[10];
int num = 0;
//生产者生产产品
public synchronized void push(Product product){
if (num==storehouse.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storehouse[num] = product;
num++;
//生产了产品,通知消费者消费(相当于将处于wait()状态的消费者线程唤醒)
this.notifyAll();
}
//消费者消费产品
public synchronized Product pop(){
//判断有没有产品
if (num==0){
//没有的话,等待生产者生产产品
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费产品
num--;
Product product = storehouse[num];
//消费了产品,通知生产者生产
this.notifyAll();
return product;
}
}