Tuesday, 9 May 2017

18. Inter thread communication via shared object

1. Inter thread communication via shared resource (or) Thread signalling
  1. Inter thread communication means a thread can pass a signal to another thread(threads can communicate with each other).
  2. Thread signalling means, the thread to wait for signals from another thread.
  3. For instance, a thread B might wait for a signal from thread A indicating that data is ready to be processed.
  4. A simple way for threads to send signals to each other is by setting the signal values in some shared object variable by the threads.
  5. Thread B which is to process the data is waiting for data to become available for processing. In other words, it is waiting for a signal from thread A which causes setHasDataToProcess() to return true. Here is the loop that thread B is running in, while waiting for this signal.
  6. Notice how the while loop keeps executing until setHasDataToProcess() returns true. This is called busy waiting. The thread is busy while waiting.


class Display {

public synchronized void wish(String name, MySignal signal) {
System.out.println("current thread is = "+Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName()+" is waiting for signal");
while(!signal.getHasDataToProcess()){
// empty logic
}
System.out.println(Thread.currentThread().getName()+" is out from signal");
signal.setHasDataToProcess(false);
}
}
------------------------------------------------------------------------------------------------------------
class MySignal {

private boolean hasDataToProcess = false;

public synchronized boolean getHasDataToProcess() {
return this.hasDataToProcess;
}

public synchronized void setHasDataToProcess(boolean hasData) {
this.hasDataToProcess = hasData;
}
}
------------------------------------------------------------------------------------------------------------
class MyThread extends Thread {

Display d;
String name;
MySignal signal;

MyThread(Display d, String name, MySignal signal) {
this.d = d;
this.name = name;
this.signal = signal;
}

public void run() {
d.wish(name, signal);
}
}
------------------------------------------------------------------------------------------------------------
public class ThreadDemo {

public static void main(String[] args) throws Exception {

Display d1 = new Display();
Display d2 = new Display();
MySignal signal = new MySignal();
MyThread thread1 = new MyThread(d1, "Rama", signal);
MyThread thread2 = new MyThread(d1, "Seetha", signal);
thread1.start();
thread2.start();
Thread.sleep(2000);
System.out.println("giving signal");
signal.setHasDataToProcess(true);
Thread.sleep(2000);
System.out.println("giving signal");
signal.setHasDataToProcess(true);
}
}




No comments:

Post a Comment

3. Java Program to create Binary Tree