问题

避免Java多线程中僵局的策略之一是使用超时. 假设,一个线程已经获得对一个资源的锁定,现在等待对另一个资源的锁定.在一段时间之后,如果它无法在resource2上获取锁,则它应该停止在resource2上等待锁定.此外,它应该在resource1上发布锁定.因此将避免死锁.

但是如何在Java中实现它?如何显式地“释放”锁?如何定义超时等待锁.

什么是确切的java命令和语法.请任何hello-worldshell示例?

  最佳答案

这是一个带有2个锁和2个线程的人造示例,尝试以不同的顺序获取它们.没有超时,代码将陷入僵局.

 public static void main(String[] args) throws Exception {
    final ReentrantLock lock1 = new ReentrantLock();
    final ReentrantLock lock2 = new ReentrantLock();
    Runnable try1_2 = getRunnable(lock1, "lock 1", lock2, "lock 2");
    Runnable try2_1 = getRunnable(lock2, "lock 2", lock1, "lock 1");
    new Thread(try1_2).start();
    new Thread(try2_1).start();
}

private static Runnable getRunnable(final ReentrantLock lock1, final String lock1Name, final ReentrantLock lock2, final String lock2Name) {
    return new Runnable() {
        @Override
        public void run() {
            try {
                if (lock1.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println(lock1Name + " acquired in thread " + Thread.currentThread());
                    if (lock2.tryLock(1, TimeUnit.SECONDS)) {
                        System.out.println(lock2Name + " acquired in thread " + Thread.currentThread());
                        Thread.sleep(2000);
                    } else {
                        System.out.println("Could not acquire "+lock2Name + " in thread " + Thread.currentThread());
                        lock1.unlock();
                        System.out.println(lock1Name + " released in thread " + Thread.currentThread());
                    }
                } else {
                    System.out.println("Could not acquire " + lock1Name + " in thread " + Thread.currentThread());
                }
            } catch (InterruptedException e) {
                //you should not ignore it
            } finally {
                if (lock1.isHeldByCurrentThread()) lock1.unlock();
                if (lock2.isHeldByCurrentThread()) lock2.unlock();
            }
        }
    };
}
 

  相同标签的其他问题

javamultithreadinglockingtimeoutdeadlock