/*线程间的通信
使用Lock接口,
condition对象中实现同步中的wait、notify、notifyAll方法,condition对象可以从Lock中的newCondition来获取
*/
import java.util.concurrent.locks.*;
class ProConDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
new Thread(new Produce(res)).start(); //匿名创建线程
new Thread(new Consumer(res)).start();
new Thread(new Produce(res)).start();
new Thread(new Consumer(res)).start();
}
}
class Resource
{
private String name;
private int count=0;
boolean flag = false; //标志位
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition(); //获取一个produce的condition对象
private Condition condition_con = lock.newCondition(); //获取一个consumer的condition对象
//Resource(String name){ this.name = name+"...."+count++; }
void set(String name)throws InterruptedException //condition对象中await()方法会跑出异常
{
lock.lock();
try
{
while(flag) //当标志变量为true时,即已经生产了,但还没有消费,故要等待
condition_pro.await();
this.name = name;
System.out.println(Thread.currentThread().getName()+this.name+"..生产.."+ ++count);
flag = true; //设置true表示已经生产了
condition_con.signal(); //唤醒consumer中的线程
}
finally
{
lock.unlock();
}
}
void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag) //当还没有生产的时候,等待
condition_con.await();
System.out.println(Thread.currentThread().getName()+name+"...消费......."+count);
flag = false; //标志已经消费了
condition_pro.signal(); //唤醒produce中的线程
}
finally
{
lock.unlock();
}
}
}
class Produce implements Runnable
{
private Resource res;
Produce(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch (InterruptedException e)
{
}
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch (InterruptedException e)
{
}
}
}
}
线程间的通信
最新推荐文章于 2024-12-06 16:56:27 发布