zoukankan      html  css  js  c++  java
  • 死锁

    多线程死锁:同步中嵌套同步,导致锁无法释放

    模拟死锁的情况:

    public class TrainThread implements Runnable {
    
        // 定义初始化票100张
        private int ticketCount = 100;
    
        private Object object = new Object();
    
        public boolean flag = true;
    
        public void run() {
    
            if (flag) {
                while (true) {
                    synchronized (object) { // 对象锁
                        sale();
                    }
                }
    
            } else {
                while (true) {
                    sale();
                }
    
            }
    
        }
    
        private synchronized void sale() { // this锁
            synchronized (object) {
                if (ticketCount > 0) {
                    try {
                        Thread.sleep(40);
                    } catch (Exception e) {
    
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + (100 - ticketCount + 1 + "张票"));
                    ticketCount--;
                }
            }
        }
    
    }
    public class App {
        public static void main(String[] args) throws InterruptedException {
            TrainThread trainThread = new TrainThread();
            
            //模拟了两个线程,必须都用同一个Runnable 的子类对象,才能叫 实现资源的共享
            Thread thread1 = new Thread(trainThread);
            Thread thread2 = new Thread(trainThread);
            thread1.start();
            thread1.sleep(40);
            trainThread.flag = false;
            thread2.start();
        }
    
    }

    两个线程,线程1 进入 对象锁,然后开始sale(),线程1 占据了this 锁(会放开),占据了对象锁(长期)

    线程2 进入了sale(),占据了this 锁,因为对象锁被线程1 占据,所以不能继续执行,同时因为占据了this 锁,线程1 也进入不了,产生死锁

  • 相关阅读:
    [SDOI2017]新生舞会
    [SCOI2007]最大土地面积
    [JLOI2014]松鼠的新家
    [AHOI2009]中国象棋
    【转载】树链剖分.By.Xminh
    HGOI20180904(NOIP2018模拟sxn出题)
    HGOI20180831 NOIP2018模拟
    【字符串算法1】 再谈字符串Hash(优雅的暴力)
    【字符串算法2】浅谈Manacher算法
    【字符串算法3】浅谈KMP算法
  • 原文地址:https://www.cnblogs.com/pickKnow/p/11017864.html
Copyright © 2011-2022 走看看