用Synchronized實現死鎖

今天看到羣裏有人說面試遇到寫一個死鎖的問題,忽然就想試着寫一下,僅供參考java

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

    }
}
相關文章
相關標籤/搜索