首页 > 代码库 > java利用lock和unlock实现消费者与生产者问题(多线程)
java利用lock和unlock实现消费者与生产者问题(多线程)
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockAndUnlockDemo { public static void main(String[] args) { Clerk2 c=new Clerk2(); Thread t=new Thread(new Producer2(c)); Thread t1=new Thread(new Consumer2(c)); t.start(); t1.start(); } } class Clerk2{ private int product=0;//生产者生产的数量给店员 private Lock lock = new ReentrantLock(); private Condition condition_pro = lock.newCondition(); private Condition condition_con = lock.newCondition(); public void addproduct(){ lock.lock(); try { if(this.product>5){ try { condition_con.await(); } catch (InterruptedException e) { e.printStackTrace(); } }else{ product++; System.out.println("生产了第"+product+"个商品"); condition_con.signal(); } }finally { lock.unlock(); } } public void getproduct(){ lock.lock(); try { if(this.product<=0){ try { condition_con.await(); } catch (InterruptedException e) { e.printStackTrace(); } } else{ System.out.println("消费者买走了第"+product+"个商品"); product--; condition_pro.signal(); } } finally { lock.unlock(); } } } class Producer2 implements Runnable{ private Clerk2 clerk; public Producer2(Clerk2 clerk) { super(); this.clerk = clerk; } public void run() { System.out.println("开始生产商品"); while(true){ try { Thread.sleep((int)(Math.random()*10)*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clerk.addproduct(); } } } class Consumer2 implements Runnable{ private Clerk2 clerk; public Consumer2(Clerk2 clerk) { super(); this.clerk = clerk; } public void run() { System.out.println("消费者买走商品"); while(true){ try { Thread.sleep((int)(Math.random()*10)*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clerk.getproduct(); } } }
本文出自 “橙子的成长记录” 博客,请务必保留此出处http://azhome.blog.51cto.com/9306775/1547231
java利用lock和unlock实现消费者与生产者问题(多线程)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。