/*
需求:
单生产单消费
思路:
一个线程用来生产,一个线程用来消费
步骤:
1. 创建资源对象
2. 创建线程任务
3. 创建一个生产线程,一个消费线程
4. 开启线程
*/
/*
描述资源
*/
class Resource
{
private String name;
private int num = 1;
private boolean flag = false;
/*
生产
*/
public synchronized void set(String name)
{
if(flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
this.name = name + num;
System.out.println(Thread.currentThread().getName()+"......生产......"+this.name);
num++;
System.out.println("num =" + num);
flag = true;
notify();
}
/*
消费
*/
public synchronized void out()
{
if(!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
System.out.println("------"+ Thread.currentThread().getName()+"......消费......" + this.name);
num--;
flag = false;
notify();
}
}
/*
生产者
*/
class Producer implements Runnable
{
private Resource r;
public Producer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("烤鸭");
}
}
}
/*
消费者
*/
class Consumer implements Runnable
{
private Resource r;
public Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class ProducerConsumer
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro_runnable = new Producer(r);
Consumer con_runnable = new Consumer(r);
Thread pro_thread = new Thread(pro_runnable);
Thread con_thread = new Thread(con_runnable);
pro_thread.start();
con_thread.start();
}
}
生产者消费者示例一
最新推荐文章于 2022-03-20 13:42:25 发布