您的位置:首页 > 其它

多线程通信经典问题——生产者消费者

2017-03-20 22:17 169 查看
/**
* 多线程通信经典案例:生产者消费者
* 多生产者、多消费者
* @author Ranphy
*
*/
class Src{
private String name;
private int count=1;
private boolean flag=false;

public synchronized void set(String name){
while(flag){            //从if改成while是因为当有多个生产者和消费者出现的时候容易出现多个消费者共享一个生产者
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"---生产者---"+this.name);
flag=true;
this.notifyAll();//若使用notify()会发生死锁现象
}
public synchronized void out(){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"---消费者---------"+this.name);
flag=false;
this.notifyAll();
}
}
class Product implements Runnable{
private Src r;
public Product(Src r) {
this.r=r;
}
@Override
public void run() {
while(true){
r.set("牛肉");
}
}

}
class Customer implements Runnable{
private Src r;
public Customer(Src r) {
this.r=r;
}
@Override
public void run() {
while(true){
r.out();
}
}

}
public class ProductCustomerDemo {
pub
4000
lic static void main(String[] args) {
Src r=new Src();
Product pro=new Product(r);
Customer cust=new Customer(r);
Thread t0=new Thread(pro);
Thread t1=new Thread(pro);
Thread t2=new Thread(cust);
Thread t3=new Thread(cust);
t0.start();
t1.start();
t2.start();
t3.start();
}
}


在JDK1.5以后将同步和锁封装成了对象,并将操作锁的隐式方式定义到了该对象中,将隐式动作变成了显示动作。即实现lock接口并通过实现类进行创建对象。lock替代了synchronized方法和语句的使用,可以在一个锁上加上多组监视器;condition替代了object监视器wait、notify等方法的使用 ,将监视器方法单独进行封装,可以任意锁进行组合。以便随时可以跟锁进行绑定。

//创建一个锁对象
Lock lock=new ReentrantLock();
//通过已有的锁获取该锁上的监视器对象
//Condition con=lock.newCondition();
//通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者
Condition pro_con=lock.newCondition();
Condition cust_con=lock.newCondition();
public  void set(String name){
lock.lock();
try {
while(flag){
//从if改成while是因为当有多个生产者和消费者出现的时候容易出现多个消费者共享一个生产者
try {
//con.await();
pro_con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"---生产者---"+this.name);
flag=true;
//con.signalAll();//若使用signal()会发生死锁现象
cust_con.signal();//用来唤醒另一个锁
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public  void out(){
lock.lock();
try {
while(!flag){
try {
cust_con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"---消费者-----"+this.name);
flag=false;
pro_con.signalAll();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: