Interthread Communication in Java

Interthread Communication in Java

Ads

Tutorials   
Java final method Assert in Java Final method in java Autoboxing in Java assert In Java JDBC batch insert using Java bean class Java Singleton Pattern Java Collection API - Java Tutorials Stack Overflow - Java Tutorials End of Year Puzzle The link to the outer class,java tutorial,java tutorials Orientating Components Right to Left,java newsletter,java,tutorial Non-virtual Methods in Java - java tutorials Multicasting in Java - java tutorials,tutorial Creation Time Comparison of Multi Dimensional Array- Java Tutorials Making Exceptions Unchecked - java tutorial,java tutorials Making Enumerations Iterable - JDK 5 Example Which is Faster - LinkedList or ArrayList? LinkedHashMap - Java Tutorials HashMap and HashCode JDK 1.4 the NullPointerException - Java Tutorials Java HashMap - Java Tutorials Java GC java awt package tutorial Java Multi Dimensions Array - Java Tutorials Java HashSet  - Java Tutorials Java Field Initialisation - Java Tutorials Java Comments - Java Tutorials J2EE Singleton Pattern - Design Pattern Tutorials Java - JDK Tutorials garbage collection in java Final Methods - Java Tutorials Exceptional Constructors - Java Tutorials Double-checked locking,java tutorials,java tutorial Disassembling Java Classes - Java Tutorials Java Deadlocks - Java Deadlocks Tutorials, Deadlocks in Java Commenting out your code - Java Tutorials Class names don't identify a class - Java Tutorials Causing Deadlocks in Swing Code Exception in Java - Java Tutorials Catching Exceptions in GUI Code - Java Tutorials boolean comparisons - tutorial Interthread Communication in Java BASIC Java - Java Tutorials Thread Deadlocks - Java Tutorials Autoboxing unboxing in Java - Java Tutorials Assertion in Java Appending Strings - Java Tutorials Anonymous Inner Classes - Anonymous Inner Classes tutorial Assertion in java
Ads

Interthread Communication in Java

As you know about producer-consumer problem of thread. In this problem one thread is producing data and another is consuming it, This problem become worst when produce needs to wait until the consumer is finished.

In a polling system, many CPU cycle is wasted by the consumer while waiting for the producer to produce. After finishing producer, producer wait for the consumer to finish. This would waste more CPU cycles.

To avoid wasting of cycle or polling, interthread communication is a good way.  Given below some function helpful in interthread communication :

Methods Description
wait( ) This method tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
notify( ) This method wakes up the first thread that called wait( ) on the same object.
notifyAll( )  This method wakes up all the threads that called wait( ) on the same object.c The highest
priority thread will run first.

EXAMPLE

In the given below Example, it has four classes. The 'Queue' class is the class which we are trying to synchronize. 'Producer' class are producing queue entries. 'Consumer' Class consuming queue entries. And the class 'InterthreadDemo' which create 'Producer', and 'Consumer' and 'Queue'. Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it.

package corejava;

class Queue {
int n;
boolean valueSet = false;

synchronized int get() {
if (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n) {
if (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable {
Queue q;

Producer(Queue q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {
Queue q;

Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {
while (true) {
q.get();
}
}
}

public class InterthreadDemo {
public static void main(String args[]) {
Queue q = new Queue();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>java InterthreadDemo
Press Control-C to stop.
Put: 0
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3

The above given output is terminated forcibly by pressing Ctrl-C key.

 

Advertisements

Ads
Share on Google+Share on Google+

Interthread Communication in Java

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Interthread Communication in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads