
Java의 Thread 클래스에서 notify() 메서드는 한 쓰레드가 다른 쓰레드에 알림을 보내는 용도로 사용됩니다. notify() 메서드는 wait() 메서드가 호출된 쓰레드에게만 알림을 보냅니다.
wait() 메서드와 notify() 메서드가 동시에 호출될 경우, notify() 메서드는 wait() 메서드가 호출된 쓰레드에게만 알림을 보냅니다. 만약 notify() 메서드가 호출된 쓰레드가 wait() 메서드를 호출하지 않은 경우, notify() 메서드는 아무런 효과가 없습니다.
notifyAll() 메서드는 모든 쓰레드에 알림을 보냅니다. notify() 메서드와의 차이점은 notify() 메서드는 한 쓰레드에게만 알림을 보낸다면, notifyAll() 메서드는 모든 쓰레드에게 알림을 보냅니다.
예를 들어, 다음과 같은 코드를 살펴보겠습니다.
#hostingforum.kr
java
public class NotifyExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("쓰레드 1: wait() 메서드 호출");
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("쓰레드 1: notify() 메서드 호출");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("쓰레드 2: notify() 메서드 호출");
lock.notify();
}
});
thread1.start();
thread2.start();
}
}
위 코드에서 thread1 쓰레드는 wait() 메서드를 호출하고, thread2 쓰레드는 notify() 메서드를 호출합니다. thread1 쓰레드는 notify() 메서드가 호출된 쓰레드에게만 알림을 받을 수 있습니다.
notifyAll() 메서드는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
java
public class NotifyAllExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("쓰레드 1: wait() 메서드 호출");
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("쓰레드 1: notifyAll() 메서드 호출");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("쓰레드 2: notifyAll() 메서드 호출");
lock.notifyAll();
}
});
thread1.start();
thread2.start();
}
}
위 코드에서 thread1 쓰레드는 notifyAll() 메서드를 호출하여 모든 쓰레드에게 알림을 보냅니다.
2025-07-11 08:26