Thread signaling refers to a mechanism where one thread communicates with another thread to indicate that a certain condition or event has occurred. This can be achieved using various synchronization techniques such as wait-notify, condition variables, semaphores, or specialized thread-safe classes.
Program
This program illustrates thread signaling with an example involving a Teacher thread and a Student thread. Assume we have a scenario where the Teacher thread needs to signal the Student thread to start a quiz after preparing the questions.
//ThreadSignalingDemo.java class Classroom { // Flag to indicate whether the quiz is ready private boolean quizReady = false; public synchronized void prepareQuiz() { // Teacher prepares the quiz questions System.out.println("Teacher is preparing the quiz..."); // Simulate some delay in preparing the quiz try { Thread.sleep(2000); // 2 seconds } catch (InterruptedException e) { e.printStackTrace(); } // Quiz is ready quizReady = true; // Notify all waiting students that quiz is ready notifyAll(); } public synchronized void takeQuiz() { // Student waits until quiz is ready while (!quizReady) { try { wait(); // Wait until notified by the Teacher } catch (InterruptedException e) { e.printStackTrace(); } } // Start taking the quiz System.out.println("Student is taking the quiz..."); } } public class ThreadSignalingDemo { public static void main(String[] args) { Classroom classroom = new Classroom(); // Create Teacher thread Thread teacherThread = new Thread(() -> { classroom.prepareQuiz(); }); // Create Student thread Thread studentThread = new Thread(() -> { classroom.takeQuiz(); }); // Start both threads teacherThread.start(); studentThread.start(); } } /* C:>javac ThreadSignalingDemo.java C:>java ThreadSignalingDemo Teacher is preparing the quiz... Student is taking the quiz... */