首页 > 其他 > 详细

jvm内置锁synchronized不能被中断

时间:2018-10-05 00:15:54      阅读:427      评论:0      收藏:0      [点我收藏+]

很久没看技术书籍了,今天看了一下《七周七并发模型》前面两章讲的java,写的还是有深度的。看到了一个有demo,说jvm内置锁synchronized是不能被中断的。照着书上写了个demo,验证了一下,是不能被中断

/**
 * @Author: 
 * @Description: jdk内置锁不能被中断
 * @Date: Created in : 2018/10/4 下午11:34
 **/
public class Uninterruptible {
    private static final Object o1 = new Object();
    private static final Object o2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        t2.start();
        Thread.sleep(2000);
        System.out.println("before interrupt");
        t1.interrupt();
        t2.interrupt();
        System.out.println("end interrupt");
        t1.join();
        t2.join();
    }

    static Thread t1 = new Thread(() -> {
       synchronized (o1){
           try {
               System.out.println("start t1");
               Thread.sleep(1000);
               synchronized (o2){
                   System.out.println("t1 lock o2");
               }
           } catch (InterruptedException e) {
               System.out.println("t1 interrupted");
               e.printStackTrace();
           }
       }
    });

    static Thread t2 = new Thread(() -> {
       synchronized (o2){
           try {
               System.out.println("start t2");
               Thread.sleep(1000);
               synchronized (o1){
                   System.out.println("t2 lock o1");
               }
           } catch (InterruptedException e) {
               System.out.println("t2 intterrupted");
               e.printStackTrace();
           }
       }
    });
}

 

jvm内置锁synchronized不能被中断

原文:https://www.cnblogs.com/luckygxf/p/9743847.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!