创建两个线程竞争持有一个锁
public class thread {
private static final Object lock = new Object();
public static void main(String[] args) {
while(true) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1 acquired the lock.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 released the lock.");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 acquired the lock.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 released the lock.");
}
});
thread1.start();
thread2.start();
}
}