1,两把锁的代码:
package demo3;
public class LockB {
private LockB(){
}
public static LockB lockB=new LockB();
}
package demo3;
public class LockA {
private LockA(){
}
public static LockA lockA=new LockA();
}
Runnable对象的代码:
package demo3;
public class DeadLock implements Runnable{
private boolean flag;
public DeadLock(boolean flag){
this.flag=flag;
}
@Override
public void run() {
if(flag){
synchronized (LockA.lockA){
System.out.println("if----lockA");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LockB.lockB){
System.out.println("if----lockB");
}
}
}
else {
synchronized (LockB.lockB){
System.out.println("else----lockB");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LockA.lockA){
System.out.println("else----lockA");
}
}
}
}
}
最后的测试代码:
package demo3;
public class DeadLockTest {
public static void main(String[] args) {
Runnable runnable=new DeadLock(true);
Runnable runnable1=new DeadLock(false);
Thread thread=new Thread(runnable);
Thread thread1=new Thread(runnable1);
thread.start();
thread1.start();
}
}
输出
if----lockA
else----lockB