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();
}

 

posted @ 2018-12-29 14:38  SasaL  Views(144)  Comments(0Edit  收藏  举报