/*
生产者消费者问题,这里实现的是生产一个,消费一个,生产一个,消费一个
生产者有生产任务
消费者有消费任务
生产和消费可以同时执行
所以使用多线程
需要描述生产任务
需要描述消费任务
生产的是产品
消费的是产品
需要描述产品
*/
//描述产品
class Product{
private String name;
private int count;
private boolean flag;
//生产产品的功能
public synchronized void produce(String name){
if(flag){
try{wait();}catch(InterruptedException e){e.printStackTrace();}
}
this.name = name+"..."+count;
System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);
count++;
flag = true;
notify();
}
//生产的时候不能消费,消费的时候不能生产,否则会出现安全问题
//消费产品的功能
public synchronized void consume(){
if(!flag){
try{wait();}catch(InterruptedException e){e.printStackTrace();}
}
System.out.println(Thread.currentThread().getName()+"...消费了..."+this.name);
flag = false;
notify();
}
}
//生产任务
class Producer implements Runnable{
private Product pro;
public Producer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.produce("笔记本");
}
}
}
//消费任务
class Consumer implements Runnable{
private Product pro;
public Consumer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.consume();
}
}
}
class test{
public static void main(String[] args){
Product pro = new Product();
Producer producer = new Producer(pro);
Consumer consumer = new Consumer(pro);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
Java——生产者消费者多线程实现
最新推荐文章于 2021-09-24 16:18:09 发布