package com.company.javaThreadTest; /** * Created by likailong on 2016/10/24. * username=a username=b 出现死锁 */ public class DeathLock implements Runnable { public String username; private Object lock1=new Object(); private Object lock2=new Object(); public void setFlag(String username){ this.username=username; } @Override public void run() { if(username.equals("a")){ synchronized(lock1){ try { System.out.println("username=" + username); Thread.sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); } synchronized(lock2){ System.out.println("按照lock1 lock2执行"); } } }if(username.equals("b")){ synchronized(lock2){ try { System.out.println("username=" + username); Thread.sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); } synchronized(lock1){ System.out.println("按照lock2 lock1执行"); } } } } public static void main(String [] args) throws InterruptedException { DeathLock deathLock=new DeathLock(); deathLock.setFlag("a"); Thread t=new Thread(deathLock); t.start(); Thread.sleep(100); deathLock.setFlag("b"); Thread t2=new Thread(deathLock); t2.start(); } }