Java 可中断锁定对可重入锁定的实际使用
这种方法实际上使用了什么?我读过这本书,但我不太清楚。有人能用其他的话来表达吗?逻辑与所有可中断阻塞方法相同:它允许线程立即对另一个线程发送给它的Java 可中断锁定对可重入锁定的实际使用,java,concurrency,locking,reentrantlock,Java,Concurrency,Locking,Reentrantlock,这种方法实际上使用了什么?我读过这本书,但我不太清楚。有人能用其他的话来表达吗?逻辑与所有可中断阻塞方法相同:它允许线程立即对另一个线程发送给它的中断信号做出反应 如何使用此特定功能取决于应用程序设计。例如,它可以用来杀死池中所有等待获得锁的线程。lockinterruptbly()如果锁已经被另一个线程持有,并且将等待直到获得锁,则可能会被阻塞。这与常规的lock()相同。但是如果另一个线程中断,等待的线程lockinterruptbly()将抛出InterruptedException尝试通
中断信号做出反应
如何使用此特定功能取决于应用程序设计。例如,它可以用来杀死池中所有等待获得锁的线程。lockinterruptbly()
如果锁已经被另一个线程持有,并且将等待直到获得锁,则可能会被阻塞。这与常规的lock()
相同。但是如果另一个线程中断,等待的线程lockinterruptbly()
将抛出InterruptedException
尝试通过下面的代码示例来理解这个概念
代码示例:
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()时,将等待来自另一个线程的中断信号,除非lock立即可用以获取它?。发送中断信号的线程一直持有锁,直到发出中断信号为止?任何线程都可以中断该线程,它不需要是持有锁的线程。Java线程中断不同于硬件或操作系统中断。中断传递是同步的、非抢占式的,而不是异步的、抢占式的,也就是说,它们不会在任意点发生,也不会暂停(稍后恢复)正在运行的代码。程序必须显式地测试它们。那么,你是说,lockInterruptibly
显式地连续测试它们吗?@overexchange它不必连续测试它们,因为它要么立即返回,要么被挂起。如果另一个线程抛出它的interrupted
标志,它将得到通知,当它恢复时,它将抛出InterruptedException
我认为ReentrantLock r=new ReentrantLock();是否应将其放置在运行块之外?
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