Java Notes_Unit4_Multithreading - Google Docs
Java Notes_Unit4_Multithreading - Google Docs
Starting Thread-2 currently running thread, which is the thread that invokes this method.5)
Running Thread-1 public static void dumpStack():- Prints the stacktrace for the currently
Thread: Thread-1, running thread, which is useful when debugging a multithreaded application.
4 Running Thread
2 Thread: Thread Example
2, 4 he following ThreadClassDemo program demonstrates some of these methods
T
Thread: Thread-1, 3 of the Thread class. Consider a class DisplayMessage which implements
Thread: Thread-2, 3 Runnable −
Thread: Thread-1, 2 // Create a thread to implement Runnable
Thread: Thread-2, 2 public class DisplayMessage implements Runnable {
Thread: Thread-1, 1 private String message;
public DisplayMessage(String message) {
Thread: Thread-2, 1
this.message = message;
Thread Thread-1 exiting.
}
Thread Thread-2 exiting.
public void run() {
Thread Methods
while(true) {
Following is the list of important methods available in the Thread class.
1)public void start():- Starts the thread in a separatepath of execution, then
System.out.println(message);
invokes the run() method on this Thread object. }
2)public void run():- If this Thread object was instantiatedusing a }
separate Runnable target, the run() method is invoked on that Runnable }
object. // Create a thread to extentd Thread
3)public final void setName(String name):-Changesthe name of the Thread public class GuessANumber extends Thread
object. There is also a getName() method for retrieving the name.4)public final {private int number;
public GuessANumber(int number) { ystem.out.println("main() is
S
this.number = number; ending...");
} }
public void run() { }
int counter = 0; This will produce the following result. You can try this example again and again
int guess = 0; and you will get a different result every time.
do { Output
guess = (int) (Math.random() * 100 + 1); Starting hello thread...
System.out.println(this.getName() + " guesses " + guess); Starting goodbye thread...
counter++; Hello
} while(guess != number); Hello
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**"); Hello
} Hello
} Hello
Following is the main program, which makes use of the above-defined classes − Hello
public class ThreadClassDemo { Goodby
public static void main(String [] args) { e
Runnable hello = new DisplayMessage("Hello"); Goodby
Thread thread1 = new Thread(hello); e
thread1.setDaemon(true); Goodby
thread1.setName("hello");
e
System.out.println("Starting hello thread..."); Goodby
thread1.start(); e
Goodby
unnable bye = new
R e
DisplayMessage("Goodbye"); Thread thread2 = ......
new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY); Inter-thread communication in Java
thread2.setDaemon(true); Inter-thread communication or Co-operation is all about allowing synchronized
System.out.println("Starting goodbye thread..."); threads to communicate with each other.
thread2.start(); Cooperation (Inter-thread communication) is a mechanism in which a thread is
System.out.println("Starting thread3..."); paused running in its critical section and another thread is allowed to enter (or
Thread thread3 = new lock) in the same critical section to be executed.It is implemented by following
GuessANumber(27); thread3.start(); methods of Object class:
try { wait() notify()
thread3.join(); notifyAll()
}catch(InterruptedException e) { 1)wait() method:- Causes current thread to releasethe lock and wait until either
System.out.println("Thread interrupted."); another thread invokes the notify() method or the notifyAll() method for this object,
} or a specified amount of time has elapsed.
System.out.println("Starting thread4..."); The current thread must own this object's monitor, so it must be called from the
Thread thread4 = new synchronized method only otherwise it will throw exception.
GuessANumber(75); public final void wait()throws InterruptedException waits until object is notified.
thread4.start(); public final void wait(long timeout)throws InterruptedException waits for the
specified amount of time. yThread t1=new MyThread();
M
2)notify() method- Wakes up a single thread thatis waiting on this object's MyThread t2=new MyThread();
monitor. If any threads are waiting on this object, one of them is chosen to be t1.start();
awakened. The choice is arbitrary and occurs at the discretion of the t2.start();
implementation. System.out.println(t1.isAlive());
Syntax: System.out.println(t2.isAlive());
public final void notify() }
3)notifyAll() method:- Wakes up all threads thatare waiting on this object's }
monitor. Syntax: Output :
public final void notifyAll()
r1
oining threads
J
true
Sometimes one thread needs to know when other thread is terminating. In
true
java, isAlive() and join() are two different methods that are used to check
r1
whether a thread has finished its execution or not.
r2
he isAlive() method returns true if the thread upon which it is called is still running
T
r2
otherwise it returns false.
Example of thread without join() method
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until
ublic class MyThread extends Thread
p
the thread on which it is called terminates.
{
final void join() throws InterruptedException
public void run()
Using join() method, we tell our thread to wait until the specified thread completes
{
its execution. There are overloaded versions of join() method, which allows us to
specify time for which you want to wait for the specified thread to terminate. final System.out.println("r1 ");
void join(long milliseconds) throws InterruptedException try {
As we have seen in the Introduction to MultiThreading, the main thread must Thread.sleep(500);
always be the last thread to finish its execution. Therefore, we can use Thread }
join() method to ensure that all the threads created by the program has been catch(InterruptedException ie){ }
terminated before the execution of the main thread. System.out.println("r2 ");
}
Example of isAlive method public static void main(String[] args)
ublic class MyThread extends Thread
p {
{ MyThread t1=new MyThread();
public void run() MyThread t2=new MyThread();
{ t1.start();
System.out.println("r1 "); t2.start();
try { }
Thread.sleep(500); }
} Output :
catch(InterruptedException ie) { } r1
System.out.println("r2 "); r1
} r2
public static void main(String[] args) r2
{ In this above program two thread t1 and t2 are created. t1 starts first and after
rinting "r1" on console thread t1 goes to sleep for 500 ms. At the same time
p
1.Synchronized method.
Thread t2 will start its process and print "r1" on console and then go into sleep for
500 ms. Thread t1 will wake up from sleep and print "r2" on console similarly 2.Synchronizedblock.
thread t2 will wake up from sleep and print "r2" on console. So you will get output 3.static synchronization.
like r1 r1 r2 r2 Example of thread with join() method
2.Cooperation (Inter-thread communication in java)
public class MyThread extends Thread
{
Mutual Exclusive
public void run()
utual Exclusive helps keep threads from interfering with one another while sharing
M
{ data. This can be done by three ways in java:
System.out.println("r1 ");
try { 1.by synchronized method
Thread.sleep(500);
2.by synchronized block
}catch(InterruptedException ie){ }
System.out.println("r2 "); 3.by static synchronization
}
public static void main(String[] args) Concept of Lock in Java
{
ynchronization is built around an internal entity known as the lock or monitor.
S
MyThread t1=new MyThread(); Every object has an lock associated with it. By convention, a thread that needs
MyThread t2=new MyThread(); consistent access to an object's fields has to acquire the object's lock before
t1.start(); accessing them, and then release the lock when it's done with them.
try{
t1.join(); //Waiting for t1 to finish Java synchronized method
}catch(InterruptedException ie){}
If you declare any method as synchronized, it is known as synchronized method.
t2.start();
} } Synchronized method is used to lock an object for any shared resource.
Output :
r1 hen a thread invokes a synchronized method, it automatically acquires the lock for
W
r2 that object and releases it when the thread completes its task.
r1
r2 Synchronized Block in Java
In this above program join() method on thread t1 ensures that t1 finishes it process
ynchronized block can be used to perform synchronization on any specific
S
before thread t2 starts.
resource of the method.
Specifying time with join()
If in the above program, we specify time while using join() with t1, then t1 will uppose you have 50 lines of code in your method, but you want to synchronize
S
execute for that time, and then t2 will join it. only 5 lines, you can use synchronized block.
t1.join(1500);
If you put all the codes of the method in the synchronized block, it will work same as
Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it. the synchronized method.
1.Mutual Exclusive