用Synchronized实现死锁

package com.thread;

import java.util.Objects;

/**
 * Created by hpx on 2016/11/26.
 * @desc 死锁
 */
public class DeadLock {
    private  Object object1=new Object ();
    private  Object object2=new Object ();

    public void method1(){
        synchronized (object1){
            System.out.println (Thread.currentThread ().getName ()+":Start");
            try {
                Thread.sleep (2000);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
            synchronized (object2){
                System.out.println (Thread.currentThread ().getName ()+":End");
            }
        }
    }
    public void method2(){
        synchronized (object2){
            System.out.println (Thread.currentThread ().getName ()+":Start");
            try {
                Thread.sleep (2000);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
            synchronized (object1){
                System.out.println (Thread.currentThread ().getName ()+":End");
            }
        }
    }


    public static void main(String[] args) {
        DeadLock deadLock=new DeadLock ();
        Thread thread=new Thread (()->{deadLock.method1 ();},"T1");
        Thread thread1=new Thread (()->{deadLock.method2 ();},"T2");
        thread.start ();
        try {
            Thread.sleep (1000);
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
        thread1.start ();

    }
}

猜你喜欢

转载自blog.csdn.net/qq_26093341/article/details/80889883