Wednesday, June 15, 2016

Thread Communication example in java

Thread Communication:

In some case,two or more threads should communicate with each-other.for example,a consumer thread is waiting for a producer to produce the data.when the producer thread completes production of data,then the consumer thread should take that data and use it.

Program:

/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class Producer extends Thread
{
 StringBuffer sb;
 boolean dataprodover=false;

 public Producer()
 {
sb=new StringBuffer();
 }

 public void run()
 {
for(int i=0;i<=10;i++)
{
sb.append(i+":");

try
{
Thread.sleep(100);
System.out.println("Appending");
}
catch (InterruptedException e)
{

e.printStackTrace();
}
}

dataprodover=true;
 }

}

class Consumer extends Thread
{
 Producer prod;
 public Consumer(Producer prod)
 {
this.prod=prod;
 }

 public void run()
 {
while(!prod.dataprodover)
try
   {
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
 }
System.out.println(prod.sb);
 }
}

public class ProducerConsumerApp
{

public static void main(String[] args) {

Producer obj1=new Producer();
Consumer obj2=new Consumer(obj1);

Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();

}


}

Output:

Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
0:1:2:3:4:5:6:7:8:9:10:

Here we can improve the efficiency of communication between threads?using 3 methods:

  • obj.notify();
  • obj.notifyAll();
  • obj.wait();
So we can use these methods inside the synchronize method.

What is difference between sleep() and wait() method?

Ans: Both sleep and wait methods are used to suspend a thread execution for a specified time.When sleep() is executed inside a synchronized block,the object is still under lock.when wait() method is executed,it breaks the synchronized block,So that the object lock is removed and it is available.

Generally,sleep() is used for making a thread to wait for some time.But wait() is used in connection with notify() or notifyAll() methods in thread communication.



No comments: