生产者消费者
Object类常用的方法
方法 | 功能 |
---|---|
void wait() | 用于使得线程进入等待状态,直到其它线程调用notify()或notifyAll()方法 |
void wait(long timeout) | 用于进入等待状态,直到其它线程调用方法或参数指定的毫秒数已经过去为止 |
void notify() | 用于唤醒等待的单个线程 |
void notifyAll() | 用于唤醒等待的所有线程 |
案例描述
在一个固定大小的仓库中存放物品,当仓库不为满的时候,生产者生产,同时消费者还在消费,实现同步机制
- 仓库代码:
package 线程.ProduceAndConsumer;
public class StoreHouse {
private int cnt = 0; // 描述商品数量
public synchronized void produceProduct() {
notify();
if (cnt < 10) {
System.out.println("线程" + Thread.currentThread().getName() + "正在生产第" + (cnt + 1) + "个商品");
cnt ++;
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void produceConsumer() {
notify();
if (cnt > 0) {
System.out.println("线程" + Thread.currentThread().getName() + "正在消费第" + cnt + "个商品");
cnt --;
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 生产者代码:
package 线程.ProduceAndConsumer;
public class ProduceThread implements Runnable{
// 声明一个仓库类型的引用作为成员变量,为了能够调用仓库类中的方法 合成服用原则
private StoreHouse storeHouse;
public ProduceThread() {
}
public ProduceThread(StoreHouse storeHouse) {
this.storeHouse = storeHouse;
}
@Override
public void run() {
while (true) {
storeHouse.produceProduct();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 消费者代码:
package 线程.ProduceAndConsumer;
public class ConsumerThread implements Runnable{
private StoreHouse storeHouse;
public ConsumerThread() {
}
public ConsumerThread(StoreHouse storeHouse) {
this.storeHouse = storeHouse;
}
@Override
public void run() {
while (true) {
storeHouse.produceConsumer();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 实现类代码:
package 线程.ProduceAndConsumer;
public class Test {
public static void main(String[] args) {
StoreHouse storeHouse = new StoreHouse();
ProduceThread produceThread = new ProduceThread(storeHouse);
ConsumerThread consumerThread = new ConsumerThread(storeHouse);
Thread t1 = new Thread(produceThread);
Thread t2 = new Thread(consumerThread);
t1.start();
t2.start();
}
}