JAVA同步之ReentrantLock可中断锁的使用

来源:互联网 发布:Python Max iteritem 编辑:程序博客网 时间:2024/05/21 12:44

http://www.iteedu.com/plang/java/superjava/threadsafe/lockInterruptibly.php


以前我们用

synchronized (mutex) {
。。。。。。。
}

进行同步时必须等待别的线程释放锁后才能进入同步块,现在问题时当太长时间等待时不想再等了,怎么办?

ReentrantLock为我们实现了中断等待的方法。

class SampleSupport1 extends SampleSupport {    private final ReentrantLock lock = new ReentrantLock();    public void doSomething() throws InterruptedException {        lock.lockInterruptibly();        System.out.println(Thread.currentThread().getName());//        try {//            lock.lockInterruptibly();//        } catch (InterruptedException e) {//            //做一些其它的事,不结束线程//        }        System.out.println(Thread.currentThread().getName() + " will execute counter++.");        startTheCountdown();        try {            counter++;                    }        finally {            lock.unlock();        }    }}

外部对他的引用进行b.interrupt(); 


阅读全文
0 0
原创粉丝点击