一种不安全的写法
public class Main {
public static final Object lock1 = new Object();
public static final Object lock2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + "已经获取了lock1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + "已经获取了lock2");
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + "已经获取了lock2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + "已经获取了lock1");
}
}
}
});
thread1.start();
thread2.start();
}
}
一种安全的写法
import java.io.*;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
public class Main {
public static final ReentrantLock lock1 = new ReentrantLock();
public static final ReentrantLock lock2 = new ReentrantLock();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
// 尝试获取 lock1,等待2秒
if (lock1.tryLock(2, TimeUnit.SECONDS)) {
try {
System.out.println("Thread1: Holding lock1...");
// 尝试获取 lock2,等待2秒
if (lock2.tryLock(2, TimeUnit.SECONDS)) {
try {
System.out.println("Thread1: Holding lock1 & lock2...");
// Critical section
} finally {
lock2.unlock();
}
} else {
System.out.println("Thread1: Could not acquire lock2, releasing lock1...");
}
} finally {
lock1.unlock();
System.out.println("Thread1: releasing lock1...");
}
} else {
System.out.println("Thread1: Could not acquire lock1...");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
// 尝试获取 lock2,等待2秒
if (lock2.tryLock(2, TimeUnit.SECONDS)) {
try {
System.out.println("Thread2: Holding lock2...");
// 尝试获取 lock1,等待2秒
if (lock1.tryLock(2, TimeUnit.SECONDS)) {
try {
System.out.println("Thread2: Holding lock2 & lock1...");
// Critical section
} finally {
lock1.unlock();
}
} else {
System.out.println("Thread2: Could not acquire lock1, releasing lock2...");
}
} finally {
lock2.unlock();
System.out.println("Thread2: releasing lock2...");
}
} else {
System.out.println("Thread2: Could not acquire lock2...");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}