ReentrantLock加锁和释放锁的一般形式如下
Lock lock = new ReentrantLock();//默认使用非公平锁,如果要使用公平锁,需要传入参数true ........ lock.lock(); try { //更新对象的状态 //捕获异常,必要时恢复到原来的不变约束 //如果有return语句,放在这里 finally { lock.unlock(); //锁必须在finally块中释放 }ReentrantLock可以实现等待中断,当某现在等待时间过长,可以接受中断退出等待,如下所示:
package jalonTest;import java.util.concurrent.locks.ReentrantLock; /* write线程一直占有锁不退出,read线程在等待时收到中断可以退出等待*/public class BufferInterruptibly { PRivate ReentrantLock 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(); } } public static void main(String args[]) { BufferInterruptibly buff = new BufferInterruptibly(); final Writer2 writer = new Writer2(buff); final Reader2 reader = new Reader2(buff); writer.start(); reader.start(); new Thread(new Runnable() { public void run() { long start = System.currentTimeMillis(); for (;;) { if (System.currentTimeMillis() - start > 5000) { System.out.println("不等了,尝试中断"); reader.interrupt(); //此处中断读操作 break; } } } }).start(); } } class Reader2 extends Thread { private BufferInterruptibly buff; public Reader2(BufferInterruptibly buff) { this.buff = buff; } @Override public void run() { try { buff.read();//可以收到中断的异常,从而有效退出 } catch (InterruptedException e) { System.out.println("我不读了"); } System.out.println("读结束"); } } class Writer2 extends Thread { private BufferInterruptibly buff; public Writer2(BufferInterruptibly buff) { this.buff = buff; } @Override public void run() { buff.write(); } }前面提到的synchronized同步则不能实现中断退出!
在synchronized同步文章中利用synchronized实现了类似的功能。synchronized和ReentrantLock最大的差别还是在于高并发性。ReentrantLock对高并发性效率较高!
新闻热点
疑难解答