zoukankan      html  css  js  c++  java
  • java学习笔记 死锁

    在锁对象期间,会产生一个问题就是死锁,双方都在等在对方释放资源

    范例:

    public class Test {
        public static void main(String[] args) throws Exception {
            MyThread mt1 = new MyThread();
            MyThread mt2 = new MyThread();
            mt1.flag = 1;
            mt2.flag = 2;
            Thread t1 = new Thread(mt1);
            Thread t2 = new Thread(mt2);        
            t1.start();
            t2.start();  
        }
    }
    
    class MyThread implements Runnable {
        static Object ob1 = new Object();//注意是static
        static Object ob2 = new Object();//注意是static
        int flag = 0;
      
        public void run() {
            if (flag == 1) {
                System.out.println("flag = 1");
                synchronized (ob1) {
                    try {
                        Thread.sleep(1000);    
                    }    catch (InterruptedException e) {
                        System.out.println("休眠中断");    
                    }
                    synchronized (ob2) {
                        System.out.println("1");    
                    }
                }    
            }
            if (flag == 2) {
                System.out.println("flag = 2");
                synchronized (ob2) {
                    try {
                        Thread.sleep(1000);    
                    }    catch (InterruptedException e) {
                        System.out.println("休眠中断");    
                    }
                    synchronized (ob1) {
                        System.out.println("2");    
                    }
                }            
            }    
        }
    }

  • 相关阅读:
    Leaf-spine data center architectures
    centreon 画图x轴乱码
    二分图匹配
    牛客练习赛17
    HDU-4550-贪心
    HDU-4511-ac自动机+dp
    UVA-11761-马尔可夫/记忆化搜索
    HDU-3853-期望/dp/坑
    HDU-4405-期望dp
    zoj-3329-期望/dp/方程优化
  • 原文地址:https://www.cnblogs.com/yhwsy/p/5814086.html
Copyright © 2011-2022 走看看