这篇文章给大家介绍java中怎么利用lockInterruptibly方法实现并发,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
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方法实现并发就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。