设为首页 加入收藏

TOP

Java 并发编程中使用 ReentrantLock 替代 synchronized 关键字原语(二)
2015-12-15 23:09:27 来源: 作者: 【 】 浏览:46
Tags:Java 并发 编程 使用 ReentrantLock 替代 synchronized 关键字
ntLock?lock?=?new?ReentrantLock();? ?
? ? ?
? ? public?void?write()?{? ?
? ? ? ? lock.lock();? ?
? ? ? ? try?{? ?
? ? ? ? ? ? long?startTime?=?System.currentTimeMillis();? ?
? ? ? ? ? ? System.out.println("开始往这个buff写入数据…");? ?
? ? ? ? ? ? for?(;;)//?模拟要处理很长时间? ?
? ? ? ? ? ? {? ?
? ? ? ? ? ? ? ? if?(System.currentTimeMillis()? ?
? ? ? ? ? ? ? ? ? ? ? ? -?startTime?>?Integer.MAX_VALUE)? ?
? ? ? ? ? ? ? ? ? ? break;? ?
? ? ? ? ? ? }? ?
? ? ? ? ? ? System.out.println("终于写完了");? ?
? ? ? ? }?finally?{? ?
? ? ? ? ? ? lock.unlock();? ?
? ? ? ? }? ?
? ? }? ?
? ? ?
? ? public?void?read()?throws?InterruptedException?{? ?
? ? ? ? lock.lockInterruptibly();//?注意这里,可以响应中断? ?
? ? ? ? try?{? ?
? ? ? ? ? ? System.out.println("从这个buff读数据");? ?
? ? ? ? }?finally?{? ?
? ? ? ? ? ? lock.unlock();? ?
? ? ? ? }? ?
? ? }? ?
? ? ?
}? ?

当然,要对reader和writer做响应的修改?

public?class?Reader?extends?Thread?{? ?
? ? ?
? ? private?BufferInterruptibly?buff;? ?
? ? ?
? ? public?Reader(BufferInterruptibly?buff)?{? ?
? ? ? ? this.buff?=?buff;? ?
? ? }? ?
? ? ?
? ? @Override? ?
? ? public?void?run()?{? ?
? ? ?
? ? ? ? try?{? ?
? ? ? ? ? ? buff.read();//可以收到中断的异常,从而有效退出? ?
? ? ? ? }?catch?(InterruptedException?e)?{? ?
? ? ? ? ? ? System.out.println("我不读了");? ?
? ? ? ? }? ?
? ? ? ? ? ?
? ? ? ? System.out.println("读结束");? ?
? ? ?
? ? }? ?
? ? ?
}? ?
? ? ?
? ?
public?class?Writer?extends?Thread?{? ?
? ? ?
? ? private?BufferInterruptibly?buff;? ?
? ? ?
? ? public?Writer(BufferInterruptibly?buff)?{? ?
? ? ? ? this.buff?=?buff;? ?
? ? }? ?
? ? ?
? ? @Override? ?
? ? public?void?run()?{? ?
? ? ? ? buff.write();? ?
? ? }? ?
? ? ?
}? ?
? ? ?
public?class?Test?{? ?
? ? public?static?void?main(String[]?args)?{? ?
? ? ? ? BufferInterruptibly?buff?=?new?BufferInterruptibly();? ?
? ? ?
? ? ? ? final?Writer?writer?=?new?Writer(buff);? ?
? ? ? ? final?Reader?reader?=?new?Reader(buff);? ?
? ? ?
? ? ? ? writer.start();? ?
? ? ? ? reader.start();? ?
? ? ?
? ? ? ? new?Thread(new?Runnable()?{? ?
? ? ?
? ? ? ? ? ? @Override? ?
? ? ? ? ? ? public?void?run()?{? ?
? ? ? ? ? ? ? ? long?start?=?System.currentTimeMillis();? ?
? ? ? ? ? ? ? ? for?(;;)?{? ?
? ? ? ? ? ? ? ? ? ? if?(System.currentTimeMillis()? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? -?start?>?5000)?{? ?
? ? ? ? ? ? ? ? ? ? ? ? System.out.println("不等了,尝试中断");? ?
? ? ? ? ? ? ? ? ? ? ? ? reader.interrupt();? ?
? ? ? ? ? ? ? ? ? ? ? ? break;? ?
? ? ? ? ? ? ? ? ? ? }? ?
? ? ?
? ? ? ? ? ? ? ? }? ?
? ? ?
? ? ? ? ? ? }? ?
? ? ? ? }).start();? ?
? ? ?
? ? }? ?
}? ?

这次“读”线程接收到了lock.lockInterruptibly()中断,并且有效处理了这个“异常”。


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux 下 GCC 编译共享库控制导出.. 下一篇Objective-C语言中nil、Nil、NULL..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: