Hibernate Tutorial

(Brent) #1

TUTORIALS POINT


public class TestThread {
public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end
try {
T1.join();
T2.join();
} catch( Exception e) {
System.out.println("Interrupted");
}
}
}

This produces same result every time you run this program:


Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

Handling threads inter communication


If you are aware of interprocess communication then it will be easy for you to understand inter thread
communication. Inter thread communication is important when you develop an application where two or more
threads exchange some information.


There are simply three methods and a little trick which makes thread communication possible. First let's see all the
three methods listed below:


SN Methods with Description

1


public void wait()
Causes the current thread to wait until another thread invokes the notify().

2


public void notify()
Wakes up a single thread that is waiting on this object's monitor.

3


public void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
Free download pdf