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 也进入不了,产生死锁

  • 相关阅读:
    html 中 #include file 的用法
    人人网FED CSS编码前端开发规范
    (转载)css垂直水平居中的整理
    CSS负边距自适应布局三例
    (转载)无缝滚动图片的js和jquery两种写法
    用css3实现鼠标移进去当前亮其他变灰
    应急响应
    扫描工具介绍
    入侵检测
    安全防护与加固
  • 原文地址:https://www.cnblogs.com/pickKnow/p/11017864.html
Copyright © 2011-2022 走看看