您的位置:首页 > 编程语言 > Java开发

多线程生产者消费者Demo2_ Lock操作

2016-07-07 16:14 441 查看
immport java.util.concurrent.locks.*;
class ProducerConsumerDemo2
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/*
JDK 1.5 中的多线程升级 方案
同步 Synchronized 替换成 显式的 Lock操作
Object类里面的wait,notify,notifyAll全部变成Condition对象
该对象可以Lock锁 进行获取
该示例中,实现了本方只唤醒对方的操作。
*/
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();//新建Lock,Condition
private Condition conditon_pro = new.newCondition();//newCondition()返回用来与此 Lock 实例一起使用的 Condition 实例。
private Condition conditon_con = new.newCondition();
public void set(String name)throws InterruptedException
{
lock.lock();
try
{
while(flag)//条件判断,用于切换
condition_pro.await();//await()等待
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;//改变flag
condition.con.signal();//唤醒线程
}
finally
{
lock.unlock();//必须执行 释放 锁的动作。因此用finally
}

}
public void out()
{
lock.lock();
try
{
while(!flag)
condition_con.await();//消费者等待
System.out.println(Thread.currentThread().getName()+"...消费者.."+this.name);
flag = true;
condition_pro.signal();//生产者唤醒
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)//这里用while会无限循环,按ctrl+c终止
{
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)
{
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 Lock Java