class Test implements Runnable{
private boolean flag; Test(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{
public static final MyLock lockA= new MyLock(); public static final MyLock lockB = new MyLock();}class DemoLockTest{
public static void main(String[] arg){ Test a = new Test(true); Test b = new Test(false); Thread t1 = new Thread(a); Thread t2 = new Thread(b); t1.start(); t2.start(); }}