public class DeadLock {
private static Object lock = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
synchronized (lock){
System.out.println(Thread.currentThread().getName()+"get lock...");
synchronized (lock2){
System.out.println(Thread.currentThread().getName()+"get lock2...");
}
}
},"t1");
Thread t2 = new Thread(()->{
synchronized (lock2){
System.out.println(Thread.currentThread().getName()+"get lock2...");
synchronized (lock){
System.out.println(Thread.currentThread().getName()+"get lock...");
}
}
},"t2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("================main==========");
}
}
控制台输出:
t2get lock2...
t1get lock...
或者用如下代码也可以:
import java.util.concurrent.locks.ReentrantLock;
public class DeadLock {
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
ReentrantLock lock2 = new ReentrantLock();
Thread t1 = new Thread(()->{
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"get lock...");
lock2.lock();
try {
System.out.println(Thread.currentThread().getName()+"get lock2...");
}catch (Exception e){
}finally {
lock2.unlock();
}
}catch (Exception e){
}finally {
lock.unlock();
}
},"t1");
Thread t2 = new Thread(()->{
lock2.lock();
try {
System.out.println(Thread.currentThread().getName()+"get lock2...");
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"get lock...");
}catch (Exception e){
}finally {
lock.unlock();
}
}catch (Exception e){
}finally {
lock2.unlock();
}
},"t2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("================main==========");
}
}