교착상태를 말한다. 사진으로 간단하게 설명할 수 있다!
즉, 두개 이상의 스레드 혹은 프로세스가 서로가 가진 리소스를 기다리는 상태
mutual exclusion
리소스를 공유해서 사용할 수 없다.
Hold and wait
프로세스가 이미 하나 이상의 리소스를 취득한(hold) 상태에서 다른 프로세스가 사용하고 있는 리소스를 추가로 기다린다.(wait)
네 가지 조건 중 하나가 충족되지 않게 시스템을 디자인
-> 단점: 모두 확보한 상태일 때 2번, 3번을 모두 획득했다라고 가정 시, 2번이 매우 오래걸리는 작업이면 3번이 놀게되어 리소스 낭비가 발생,
또 만약, 2번과 3번의 리소스가 너무 인기가 많아서 오른쪽 위 프로세스는 대기를 지속하게 된다. 그렇게 되면 기아현상(Starvation)이 발생한다.
public class Main {
public static Object object1 = new Object();
public static Object object2 = new Object();
public static void main(String[] args) {
FirstThread thread1 = new FirstThread();
SecondThread thread2 = new SecondThread();
thread1.start();
thread2.start();
}
private static class FirstThread extends Thread{
@Override
public void run() {
synchronized (object1){
System.out.println("First Thread has object1's lock");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("First Thread want to have object2's lock. so wait");
synchronized (object2){
System.out.println("First Thread has object2's lock too");
}
}
}
}
private static class SecondThread extends Thread{
@Override
public void run() {
synchronized (object2){
System.out.println("Second Thread has object2's lock");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Second Thread want to have object1's lock, so wait");
synchronized (object1){
System.out.println("Second Thread has object1's lock too");
}
}
}
}
}
First Thread has object1's lock
Second Thread has object2's lock
First Thread want to have object2's lock. so wait
Second Thread want to have object1's lock, so wait
public class Main {
public static Object object1 = new Object();
public static Object object2 = new Object();
public static void main(String[] args) {
FirstThread thread1 = new FirstThread();
SecondThread thread2 = new SecondThread();
thread1.start();
thread2.start();
}
private static class FirstThread extends Thread{
@Override
public void run() {
synchronized (object1){
System.out.println("First Thread has object1's lock");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("First Thread want to have object2's lock. so wait");
synchronized (object2){
System.out.println("First Thread has object2's lock too");
}
}
}
}
private static class SecondThread extends Thread{
@Override
public void run() {
synchronized (object1){
System.out.println("Second Thread has object2's lock");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Second Thread want to have object1's lock, so wait");
synchronized (object2){
System.out.println("Second Thread has object1's lock too");
}
}
}
}
}
First Thread has object1's lock
First Thread want to have object2's lock. so wait
First Thread has object2's lock too
Second Thread has object2's lock
Second Thread want to have object1's lock, so wait
Second Thread has object1's lock too