消费者与生产者–线程java
核心代码
package homework;
/**
* 消费者Runnable
* @author : 外哥
* 邮箱 : liwai2012220663@163.com
* 创建时间:2020年12月19日 下午6:02:38
*/
public class Consumer implements Runnable{
private Goods goods ;
public Consumer(Goods goods) {
super();
this.goods = goods;
}
public void run() {
while ( true ) {
synchronized (goods) {
if ( goods.getCount() <= 0 ) {
// 如果没有产品,唤醒生产者进行生产,则消费者进入无限等待状态
try {
goods.notify();
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果有产品,则进行消费
System.out.println( Thread.currentThread().getName() + "正在消费产品" + goods.getCount() );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( Thread.currentThread().getName() + "消费了产品" + goods.getCount() );
System.out.println("--------------------------------------");
goods.setCount( goods.getCount() - 1 );
}
}
}
}
package homework;
/**
* 生产者线程类
* @author : 外哥
* 邮箱 : liwai2012220663@163.com
* 创建时间:2020年12月19日 下午5:56:11
*/
public class Producer extends Thread{
private Goods goods ;
public Producer(Goods goods, String string) {
super(string);
this.goods = goods;
}
@Override
public void run() {
// 一直生产产品
while ( true ) {
synchronized (goods) {
if ( goods.getCount() > 0 ) {
// 如果有产品,生产者进入无限等待状态
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有产品,则经过五秒钟生产产品
System.out.println( getName() + "正在生产产品" + (goods.getCount()+1) );
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 更新产品数量
goods.setCount( goods.getCount() + 1 );
System.out.println( getName() + "生产出了产品" + goods.getCount() );
// 唤醒所有消费者进行消费
goods.notify();
}
}
}
}
测试类
package homework;
/**
* 生产者和消费者案例的测试类
* @author : 外哥
* 邮箱 : liwai2012220663@163.com
* 创建时间:2020年12月19日 下午6:07:29
*/
public class Test {
public static void main(String[] args) {
Goods goods = new Goods() ;
goods.setCount(0);
// 开启生产者线程
new Producer(goods,"生产者").start();
// 开启消费者线程
Consumer consumer = new Consumer(goods) ;
new Thread(consumer,"顾客1").start();
}
}