实际使用的锁定可中断用于重新输入锁定



此方法lockInterruptibly实际使用了什么?我已经读过API,但我不太清楚。有人能用其他语言表达吗?

如果锁已经被另一个线程持有,则

lockInterruptibly()可能会阻塞,并等待锁被获取。这与常规lock()相同。但如果另一个线程中断,则等待线程lockInterruptibly()将抛出InterruptedException

逻辑与所有可中断的阻塞方法相同:它允许线程立即对另一个线程发送给它的interrupt信号做出反应。

如何使用此特定功能取决于应用程序设计。例如,它可以用来杀死池中所有等待获取锁的线程。

试着通过下面的代码示例来理解这个概念。

代码示例:

package codingInterview.thread;
import java.util.concurrent.locks.ReentrantLock;
public class MyRentrantlock {
    Thread t = new Thread() {
        @Override
        public void run() {
            ReentrantLock r = new ReentrantLock();
            r.lock();
            System.out.println("lock() : lock count :" + r.getHoldCount());
            interrupt();
            System.out.println("Current thread is intrupted");
            r.tryLock();
            System.out.println("tryLock() on intrupted thread lock count :" + r.getHoldCount());
            try {
                r.lockInterruptibly();
                System.out.println("lockInterruptibly() --NOt executable statement" + r.getHoldCount());
            } catch (InterruptedException e) {
                r.lock();
                System.out.println("Error");
            } finally {
                r.unlock();
            }
            System.out.println("lockInterruptibly() not able to Acqurie lock: lock count :" + r.getHoldCount());
            r.unlock();
            System.out.println("lock count :" + r.getHoldCount());
            r.unlock();
            System.out.println("lock count :" + r.getHoldCount());
        }
    };
    public static void main(String str[]) {
        MyRentrantlock m = new MyRentrantlock();
        m.t.start();
        System.out.println("");
    }
}

输出:

lock() : lock count :1
Current thread is intrupted
tryLock() on intrupted thread lock count :2
Error
lockInterruptibly() not able to Acqurie lock: lock count :2
lock count :1
lock count :0

使用lockInterruptibly()的线程可以被另一个线程中断。因此,对lockInterruptibly()的调用抛出了可以捕获的InterruptedException,并且可以在捕获块内完成有用的事情,比如释放持有的锁,这样导致中断发生的其他线程就可以访问释放的锁。想想这样一种情况,您有一个具有以下读写约束的通用数据结构:

  1. 单个线程负责写入公共数据结构
  2. 只有一个读者线程
  3. 当写入正在进行时,不应允许读取

为了满足上述约束,读取器线程可以使用lockInterruptibly()来获得对java.util.concurrent.locks.ReentrantLock的访问。这意味着在编写器线程的处理过程中,读取器线程可以随时中断。编写器线程可以访问读取器线程实例,并且编写器可以中断读取器。当读取器接收到中断时,在InterruptedException的catch块中,读取器应该unlock保持ReentrantLock,并等待来自写入线程的通知以继续进行。编写器线程可以使用tryLock方法获取相同的锁。读取器和写入器线程的代码片段如下所示:

读写线程访问的公共字段:

ReentrantLock commonLock = new ReentrantLock(); //This is the common lock used by both reader and writer threads.
List<String> randomWords = new ArrayList(); //This is the data structure that writer updates and reader reads from. 
CountDownLatch readerWriterCdl = new CountDownLatch(1); //This is used to inform the reader that writer is done.

读卡器:

try {
        if(!commonLock.isHeldByCurrentThread())
            commonLock.lockInterruptibly();                     
         System.out.println("Reader: accessing randomWords" +randomWords);              
    } catch (InterruptedException e) {                      
            commonLock.unlock();
            try {
                    readerWriterCdl.await();
                } 
                catch (InterruptedException e1) {
                }
    }

作者:

if(commonLock.isLocked() && !commonLock.isHeldByCurrentThread()) 
{
    readerThread.interrupt();
}
                        
boolean lockStatus = commonLock.tryLock();
if(lockStatus) {
   //Update the randomWords list and then release the lock.
   commonLock.unlock();
   readerWriterCdl.countDown();
   readerWriterCdl = new CountDownLatch(1);
}

根据Evgeniy Dorofeev的回答,我只是故意想出这样的演示,但我真的不知道它到底在哪里,可以使用。也许这个演示可以帮助一点:)

private static void testReentrantLock() {
    ReentrantLock lock = new ReentrantLock();
    Thread thread = new Thread(() -> {
        int i = 0;
        System.out.println("before entering ReentrankLock block");
        try {
            lock.lockInterruptibly();
                while (0 < 1) {
                    System.out.println("in the ReentrankLock block counting: " + i++);
                }
        } catch (InterruptedException e) {
            System.out.println("ReentrankLock block interrupted");
        }
    });
    lock.lock(); // lock first to make the lock in the thread "waiting" and then interruptible
    thread.start();
    thread.interrupt();
}

输出

before entering ReentrankLock block
ReentrankLock block interrupted

最新更新