死锁:在两个线程对同步对象具有依赖,就会出现死锁。以下是简单的示例:
package org.test.code;
public class DeadLock {
public static void main(String[] args) {
final Object resource1 = "resource1";
final Object resource2 = "resource2";
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println(Thread.currentThread().getName() + ":"
+ " locked resource 1");
synchronized (resource2) {
System.out.println(Thread.currentThread().getName()
+ ":" + " locked resource 2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println(Thread.currentThread().getName() + ":"
+ " locked resource 2");
synchronized (resource1) {
System.out.println(Thread.currentThread().getName()
+ ":" + " locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}