zoukankan      html  css  js  c++  java
  • java 线程(六)死锁

    package cn.sasa.demo4;
    
    public class ThreadDemo {
        public static void main(String[] args){
            DeadLockRunnable dead = new DeadLockRunnable();
            Thread t0 = new Thread(dead);
            Thread t1 = new Thread(dead);
            Thread t2 = new Thread(dead);
            t0.start();
            t1.start();
            t2.start();
            /**
             * 线程中出现同步的嵌套,容易发生死锁
             * 
             * Thread-1---if---locka---
             * Thread-1---if---lockb---
             * Thread-1---else---lockb---
             * Thread-0---if---locka---
             * 发生死锁
             */
        }
    }
    package cn.sasa.demo4;
    
    public class DeadLockRunnable implements Runnable{
        /**
         * 线程嵌套容易发生死锁,线程出现无限等待
         */
        public void run() {
            int flag = 100;
            while(flag > 0) {
                if(flag % 2 == 0) {
                    //先进入A同步,再进B同步
                    synchronized(Locka.locka) {
                        System.out.println(Thread.currentThread().getName() + "---if---locka---");
                        synchronized (Lockb.lockb) {
                            System.out.println(Thread.currentThread().getName() + "---if---lockb---");
                        }
                    }
                }else {
                    //先进入B同步,再进A同步
                    synchronized(Lockb.lockb) {
                        System.out.println(Thread.currentThread().getName() + "---else---lockb---");
                        synchronized (Locka.locka) {
                            System.out.println(Thread.currentThread().getName() + "---else---locka---");
                        }
                    }
                }
                flag--;
            }
        }
    }
    package cn.sasa.demo4;
    
    public class Locka {
      //单例 对象只允许创建一次
    private Locka() {} public static final Locka locka = new Locka(); }
    package cn.sasa.demo4;
    
    public class Lockb {
        private Lockb() {}
        public static final Lockb lockb = new Lockb();
    }
  • 相关阅读:
    激活Win Server 2008 R2 Datacenter
    .NET中使用EF6与连接MYSQL
    设计模式(六)——命令模式
    C#爬虫之Senlium
    GitHub入门(一)GIT配置与Hexo博客搭建
    正则表达式
    C#预处理器
    第一次炒花甲
    第一次清蒸鲈鱼
    Python traceback【转】
  • 原文地址:https://www.cnblogs.com/SasaL/p/10195893.html
Copyright © 2011-2022 走看看