LockDemo
2014-02-04 15:19
281 查看
package cn.sice; import java.util.ArrayList; import java.util.Date; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockDemo { public static void main(String[] args) { Res r = new Res(); In in = new In(r); Out out = new Out(r); new Thread(in).start(); new Thread(out).start(); } } class Res { ArrayList<String> arrList = new ArrayList(); Lock lock = new ReentrantLock(); Condition conSet = lock.newCondition(); Condition conGet = lock.newCondition(); boolean flag = false; public void set() { lock.lock(); try { while (flag) conSet.await(); arrList.add(new Date().toString()); System.out.println("SET----" + arrList.size() + "-- " + arrList.get(arrList.size() - 1) + " *** " + Thread.currentThread().getName()); flag = true; conGet.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void get() { lock.lock(); try { while (!flag) conGet.await(); System.out.println("GET----" + arrList.size() + "-----" + arrList.get(0) + " *** " + Thread.currentThread().getName()); arrList.remove(0); flag = false; conSet.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } class In implements Runnable { public void run() { while (true) { r.set(); } } private Res r; public In(Res r) { this.r = r; } } class Out implements Runnable { private Res r; public Out(Res r) { this.r = r; } public void run() { while (true) { r.get(); } } }
相关文章推荐
- 安装debian linux后的优化配置
- Linux内核编译,模块尺寸变大的解决办法
- 程序员必看的那些电影
- Initialising Memories
- tomcat的一些设置
- java学习之面试题3
- SPOJ 220 Relevant Phrases of Annihilation(后缀数组)
- 2014学习计划
- 【C++学习】迭代器的使用:vector的操作---ShinePans
- Uml 9种图 之 行为描述 之活动图和状态图
- 《CSS Mastery》读书笔记(3)
- Cracking the coding interview--Q2.1
- 《CSS Mastery》读书笔记(2)
- UiButton操作
- SPOJ #4 Transform the Expression
- Displaytag实现分页
- Codeforces Round #228 (Div. 2)
- 【转】中国人唯一不认可的成功——就是家庭的和睦,人生的平淡
- testbench中将外部数据引入输出的方法(转载)
- SQL 清日志