What is a Deadlock?
What is a Deadlock?
A deadlock is a situation in concurrent computing where two or more processes or threads are unable to proceed because each is waiting for the other to release a resource. This results in a standstill where none of the processes can continue execution. Deadlocks are a common problem in multiprocessing systems, parallel computing, and distributed systems, where resources such as locks, semaphores, or other synchronization mechanisms are used to manage access to shared resources.
For a deadlock to occur, the following four conditions must be met simultaneously:
In Java, deadlocks often occur in multithreaded applications where multiple threads need the same locks but acquire them in different orders. Here is a simple example:
public class DeadlockExample {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); } catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); } catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào