多线程生产者消费者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) { } } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- Python3写爬虫(四)多线程实现数据爬取
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序