使用ReentrantLock
来源:互联网 发布:消防车辆应知 编辑:程序博客网 时间:2024/05/16 08:31
public class TestLock {public TestLock() {// TODO Auto-generated constructor stub}public void reentrantLock() {boolean useSynchronized = false;IBuffer buff = null; if(useSynchronized){ buff = new Buffer(); }else{ buff = new BufferInterruptibly(); } final Writer writer = new Writer(buff); final Reader reader = new Reader(buff); writer.start(); reader.start(); new Thread(new Runnable() { public void run() { long start = System.currentTimeMillis(); for (;;) { // 等5秒钟去中断读 if (System.currentTimeMillis() - start > 5000) { System.out.println("不等了,尝试中断"); reader.interrupt(); break; } } } }).start();}public static void main(String[] args) {new TestLock().reentrantLock();}interface IBuffer{ public void write(); public void read() throws InterruptedException;}public class Buffer implements IBuffer{ private Object lock; public Buffer() { lock = this; } public void write() { synchronized (lock) { long startTime = System.currentTimeMillis(); System.out.println("开始往这个buff写入数据…"); for (;;)// 模拟要处理很长时间 { if (System.currentTimeMillis() - startTime > 30000) break; } System.out.println("终于写完了"); } } public void read() { synchronized (lock) { System.out.println("从这个buff读数据"); } }}class BufferInterruptibly implements IBuffer{ private ReentrantLock lock = new ReentrantLock(); public void write() { lock.lock(); try { long startTime = System.currentTimeMillis(); System.out.println("开始往这个buff写入数据…"); for (;;)// 模拟要处理很长时间 { if (System.currentTimeMillis() - startTime > 30000) break; } System.out.println("终于写完了"); } finally { lock.unlock(); } } public void read() throws InterruptedException{ lock.lockInterruptibly();// 注意这里,可以响应中断// boolean lockFlag = lock.tryLock(5, TimeUnit.SECONDS); try { System.out.println("从这个buff读数据"); } finally { lock.unlock(); } }}class Writer extends Thread { private IBuffer buff; public Writer(IBuffer buff) { this.buff = buff; } @Override public void run() { buff.write(); }}class Reader extends Thread { private IBuffer buff; public Reader(IBuffer buff) { this.buff = buff; } @Override public void run() { try { buff.read(); } catch (InterruptedException e) { System.out.println("我不读了"); } System.out.println("读结束"); }}}
0 0
- 使用ReentrantLock
- 使用ReentrantLock
- reentrantlock使用
- ReentrantLock使用
- ReentrantLock--synchronized和ReentrantLock区别及使用
- ReentrantLock的使用
- ReentrantLock的使用
- ReentrantLock的使用
- ReentrantLock的使用
- ReentrantLock Condition使用详解
- ReentrantLock的使用
- ReentrantLock的使用
- ReentrantLock的使用
- Lock的使用---ReentrantLock
- ReentrantLock可重入锁的使用场景
- ReentrantLock可重入锁的使用场景
- ReentrantLock可重入锁的使用场景
- ReentrantLock可重入锁的使用场景
- 一生难求 ---- 懂你的人
- keepalive的原理
- 第十七周项目1引用
- 2014-12-08工作总结
- qt creator调用vs编译的c的lib库
- 使用ReentrantLock
- Android 使用android-support-multidex解决Dex超出方法数的限制问题
- Bluetooth tethering不能用问题
- 一致性哈希算法 - Consistent Hashing
- 当你心情不好时,
- MAC mysql安装及设置
- 通过 Terracotta实现基于Tomcat的Web应用集群
- UITableView:改变 TableHeaderView 的高度
- Android studio项目不能编译,提示设备版本过低