Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 스레드 간 통신 방법: wait(), notify(), notifyAll() 핵심 정리

스레드 간 통신(Inter-thread Communication)이란 여러 스레드가 서로 정보를 주고받으며 협력하는 것을 의미합니다. Java에서는 주로 세 가지 메서드를 사용해 스레드 간 통신을 구현합니다.

wait()

wait() 메서드는 현재 스레드가 가지고 있는 락(lock)을 해제하도록 만듭니다. 이후 지정된 시간이 경과하거나, 다른 스레드가 해당 객체에 대해 notify() 또는 notifyAll() 메서드를 호출할 때까지 대기 상태를 유지합니다.

notify()

notify() 메서드는 현재 객체의 모니터(monitor)에서 대기 중인 여러 스레드 중 단 하나의 스레드만 깨웁니다. 어떤 스레드가 선택될지는 임의로 결정됩니다.

notifyAll()

notifyAll() 메서드는 현재 객체의 모니터에서 대기 중인 모든 스레드를 깨웁니다. 깨어난 스레드들은 락을 획득하기 위해 경쟁하게 됩니다.

예제 코드

아래 예제는 은행 고객 계좌를 모델링하여 출금과 입금 작업을 두 개의 스레드로 처리하는 코드입니다.

class BankClient {
    int balAmount = 5000;
    synchronized void withdrawMoney(int amount) {
        System.out.println("Withdrawing money");
        balAmount -= amount;
        System.out.println("The balance amount is: " + balAmount);
    }
    synchronized void depositMoney(int amount) {
        System.out.println("Depositing money");
        balAmount += amount;
        System.out.println("The balance amount is: " + balAmount);
        notify();
    }
}
public class ThreadCommunicationTest {
    public static void main(String args[]) {
        final BankClient client = new BankClient();
        new Thread() {
            public void run() {
                client.withdrawMoney(3000);
            }
        }.start();
        new Thread() {
            public void run() {
                client.depositMoney(2000);
            }
        }.start();
    }
}

실행 결과

Withdrawing money
The balance amount is: 2000
Depositing money
The balance amount is: 4000