这篇文章给大家介绍java中怎么利用lockInterruptibly方法实现并发,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新新互联,凭借10多年的成都网站设计、做网站经验,本着真心·诚心服务的企业理念服务于成都中小企业设计网站有上千多家案例。做网站建设,选成都创新互联。
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个线程由于尝试获取锁一直阻塞着:
换成lockInterruptibly后代码如下:
public class LockInterruptTest {
static ReentrantLock lock = new ReentrantLock();
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();
}
}
通过jconsole工具可以发现第2个线程被成功中断。
关于java中怎么利用lockInterruptibly方法实现并发就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。