In Java , threads communicate with each other using “wait,notify and notifyAll” APIs. Producer-Consumer is the classic example to explain these APIs. The example below tries to show how we can use inter-thread communication to read shared data when it is available. I have also tried to demonstrate use of Thread Interrupt using which we can cancel the running task, in this case exiting the application.

[sourcecode language=”java”]
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author Amit
* This Producer-Consumer example tries to read/write one shared String variable.
* This example also uses Thread interrupt concept to stop the application.
* The variable in main() are defined final so that we can use them in
* Anonymous inner class implementation of thread within main() method.
*/
public class ConsumerProducerTest {

static String data = new String();

public static void main(String args[]) {

//Declaring these variables as final so that
//I can access them inside the Anonymous inner class
//for user thread.
final Object lock = new Object();