class DeadLock implements Runnable {
private Object resourceA = new Object();
private Object resourceB = new Object();
private int count = 0;
public void run() {
if(count++ < 1) {
synchronized(resourceA) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceA 的对象锁");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
synchronized(resourceB) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceB 的对象锁");
}
}
} else {
synchronized(resourceB) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceB 的对象锁");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
synchronized(resourceA) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceA 的对象锁");
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
DeadLock deadLock = new DeadLock();
Thread t1 = new Thread(deadLock);
Thread t2 = new Thread(deadLock);
t1.start();
t2.start();
}
}
|
|