
notifyOne 함수는 notify 함수와 달리, notifyOne 함수는 특정한 쓰레드만 notify를 보내는 함수입니다. notify 함수는 모든 대기중인 쓰레드에 notify를 보내는 반면, notifyOne 함수는 대기중인 쓰레드 중에서 하나만 notify를 보냅니다.
notifyOne 함수를 사용할 때는, 다음과 같은 경우에 사용할 수 있습니다.
- 특정한 쓰레드만 notify를 보내고 싶을 때
- notify 함수를 사용하면 여러 쓰레드가 동시에 실행되는 문제가 발생할 수 있으므로, notifyOne 함수를 사용하여 하나의 쓰레드만 실행하도록 제어할 수 있습니다.
notifyOne 함수를 사용하기 위해서는, 쓰레드가 대기중인 notify를 받기 전에, 쓰레드의 이름이나 ID를 지정해야 합니다. 예를 들어, 다음 코드는 notifyOne 함수를 사용하여 쓰레드 'thread1'만 notify를 보내는 예제입니다.
#hostingforum.kr
java
public class Threaded {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("thread1: 대기중...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1: notifyOne 받음");
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2: 대기중...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2: notifyOne 받음");
});
thread1.start();
thread2.start();
thread1.notifyOne(); // thread1만 notify를 받음
}
}
notifyOne 함수를 사용하면, 쓰레드 간의 통신을 더 안전하고 효율적으로 구현할 수 있습니다.
2025-06-03 03:54