代码:
package oo; // class TestJava implements Runnable{ private boolean flag ; TestJava(boolean flag){ //把标记传进来 this.flag =flag; } public void run(){ if(flag ){ synchronized(MyLock.locka ){ System. out.println("if locka" ); synchronized(MyLock.lockb ){ System. out.println("if lockb"); } } } else{ synchronized(MyLock.lockb ){ System. out.println("else lockb" ); synchronized(MyLock.locka ){ System. out.println("else locka"); } } } } } class MyLock{ static Object locka=new Object();//写静态只为了方便调用 static Object lockb=new Object(); } public class DeadLockTest {
public static void main(String[] args) { Thread t1= new Thread(new TestJava(true)); Thread t2=new Thread( new TestJava(false)); t1.start(); t2.start(); }
} 结果:if locka
else lockb就锁住了 无法运行 |