lockInterruptibly方法是說線程在等待獲取鎖的同時還能響應線程interrupt方法的中斷請求。換句話說就是存在等待獲取鎖的同時還不能響應線程interrupt方法的中斷請求的狀況,synchronized內置鎖即是,請看測試代碼:工具
public class LockInterruptTest {測試
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(){
public void run(){
synchronized (LockInterruptTest.class) {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread t2 = new Thread(){
public void run(){
synchronized (LockInterruptTest.class) {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread t3 = new Thread(){
public void run(){
System.out.println("準備中斷t2");
t2.interrupt();
System.out.println("中斷t2");
}
};
t3.start();
}線程
}
代碼中準備了3個線程,第2個線程嘗試獲取第1個線程的鎖,第3個線程嘗試中斷第2個線程。代碼是可以正常看到「中斷t2」的,可是用jconsole工具就能看到第2個線程因爲嘗試獲取鎖一直阻塞着:blog
換成lockInterruptibly後代碼以下:io
public class LockInterruptTest {
static ReentrantLock lock = new ReentrantLock();console
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
};
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Thread t2 = new Thread() {
public void run() {
try {
lock.lockInterruptibly();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
lock.unlock();
}
}
};
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Thread t3 = new Thread() {
public void run() {
System.out.println("準備中斷t2");
t2.interrupt();
System.out.println("中斷t2");
}
};
t3.start();
}class
}請求
經過jconsole工具能夠發現第2個線程被成功中斷。
方法