Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAVA - 7 - Multithreading Programming - Doc

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 27

Chapter-7 Multithreaded Programming

Multithreading programming
• Introduction to multithreading
• The Java thread model (Life cycle of thread)
• The main thread
• Creating a thread
• Creating multiple threads.
• Using alive( ) & join( )
• Thread priorities
• Synchronization
• Inter thread communication
• Suspending, resuming, stopping threads

Introduction
• Program is a sequence of statements.
• A Program may be divided into two or more sub programs, this sub programs are
called process.
• Many Processes can be implemented at the same time in parallel (parallel Execution).
• Process can be divided into further small parts in its sub process (threads).
• That sub-process is called Thread.
• We can say “Thread” is a smallest unit of a program.
Important terms
• Multiprogramming: More than one program running at same time. That can share
same Processor.
• Multiprocessing: two or more processes of a program running at same time. They can
process on the own (different) memory location.
• Multithreading: two or more thread of a process executing in parallel. That can share
same memory location in the memory.
• Multitasking: multiple task performed at a time
Difference between Thread based and process base Multitasking

NO. Thread based Multitasking Process based Multitasking


In thread based multitasking thread is the Process is smallest unit of code that can be
1 smallest unit of code. dispatched by multitasking.
Process is dividing into number of Program is divided into number of
2 threads. (light weight process) processes. (Heavy weight process)

By :Dhara Kanzariya Page 1


Chapter-7 Multithreaded Programming

Single program can perform two or more Process based multitasking allows your
3 task simultaneously. computer to run two or more program.
Each thread of same process shared the Each process has independent execution
same state, same memory space and can units that contain their own state
communicate with each other directly. information, address spaces, and interact
4
Because they share same variable. So with each other via IPC.
threads are known as Light weight
process.
E.g. Text editor can format text a t the You can run java compiler at the same time
same time that it is printing that that you are using a text editor
5 document. These two actions are being
performed by two separate threads

By :Dhara Kanzariya Page 2


Chapter-7 Multithreaded Programming

Single threaded program


• A program which has single flow of execution are single threaded programs.
• When execute a such program ,program begins, runs through a sequence of execution
and finally ends.
• All main programs in our earlier examples are single threaded programs.
• Every program will have at least one thread.

Multithreading Concept
• Multithreading is a conceptual programming paradigm where a program ( or
process) is divided into two or more subprograms( or process),which can be
implemented at the same time in parallel.
• Java enables us to use and manage multiple flows of control in developing
programs.
• Each flow of control may be thought of as a separate tiny program, which is known
as thread that runs in parallel to others threads of the same process.
• Threads in java are subprograms of main application program and share the same
memory space, they are known as light weight process.
• Once any thread of the process initiated then the remaining threads run concurrently
and share the same resources jointly.
• Multithreading is similar to dividing a task into subtasks and assigning them to
different people for execution independently and simultaneously, to achieve a single
desire.

By :Dhara Kanzariya Page 3


Chapter-7 Multithreaded Programming

• E.g. In animation, one sub program can display an animation on the screen while
another may build the next animation to be displayed.
• Threads are extensively used in java enabled browsers such HotJava. These
browsers can download a file to the local computer, display a web page in the
window, and output another web page to a printer and so on.
• If we are working on any application that requires two more things to be done at the
same time, then threads are best to use.

Here, Java program with four threads, one main and three others. Here main thread is
designed to create and start the other three threads namely A, B and C.
Note:

• Actually, we have only one processor and therefore in reality the processor is doing
only one thing at time. However, the processor switches between the processes so fast
that it appears to all of them are being done simultaneously.

• Threads’ running in parallel does not really mean that they actually run at the same
time. Actually, all threads are running on a single processor, the flow of execution is
shared between threads.

By :Dhara Kanzariya Page 4


Chapter-7 Multithreaded Programming

• Java interpreter handles the switching of control between the threads in such a way that
it appears they are running concurrently.

Use:

 It enables programmers to do multiple things at one time.

 We can divided a long program into threads and execute them in parallel, so we can
use each and every resources efficiently.

 We can send tasks into background and continue to perform some other task in the
foreground. This increase speed of our program.

Thread life cycle


• During the life time of a thread ,there are many states it can enter, They are:

1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

A thread is always in one of these five states. It can move from one state to another via
a variety of ways.

By :Dhara Kanzariya Page 5


Chapter-7 Multithreaded Programming

Figure: Thread Life cycle Or Thread state transition Diagram


1 ) New born state
• When we create a thread object, the thread is born and is said to be in newborn state.
• The thread is not still scheduled for running.
• At this time we can do only one of following with it:
 Scheduled it for running using start () method.
 Kill it using stop () method.
• If thread scheduled ,it moves to the runnable state
• If we attempt to use any other method at this stage, an exception will be thrown.

2) Runnable state
• Runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
• The threads has joined waiting queue for execution.
• If all threads have equal priority, then they are given time slots for execution in round
robin fashion. i. e. first-come, first serve manner.
• Thread which is relinquishes (leaves) control, joins the queue at the end and again
waits for its turn. This process of assigning time to thread is known as time-slicing.
• If we want a thread to relinquish(leave) control to another thread of equal priority
before its turn comes ,then yield( ) method is used

By :Dhara Kanzariya Page 6


Chapter-7 Multithreaded Programming

3) Running state
• Running means that processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher
priority thread.
• A running thread may change its state to another state in one of the following
situations.
1) When It has been suspended using suspend ( ) method.
 A suspended thread can be reviewed by resume ( ) method.
 This is used when we want to suspend a thread for some time due to certain reason, but
do not want to kill it.

2) It has been made to sleep ( ).


 We can put a thread to sleep for a specified time period using the method sleep (time)
where time is in milliseconds.
 This means that the thread is out of the queue during this time period.
 Thread is re-enters the runnable state as soon as this time period is elapsed(over).

3) When it has been told to wait until some events occurs.


 This done using the wait ( ) method.
 The thread can be scheduled to run again using notify () method.

By :Dhara Kanzariya Page 7


Chapter-7 Multithreaded Programming

4) Blocked state
• A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state.
• This happens when the thread is suspended, sleeping or waiting in order to satisfy
certain requirements.
• A blocked thread is considered “not runnable” but not dead and therefore fully
qualified to run again.
5) Dead state
• Every thread has a life cycle. A running thread ends its life when it has completed
executing its run ( ) method.
• It is natural death. However we can kill it by sending the stop message to it as any state
thus causing a premature death for it.
• A thread can be killed as soon it is born or while it is running or even when it is in
“blocked” condition.
Main thread
• When a java program starts up, one thread begins running immediately.
• It is the one that is executed when your program begins, so it is usually called the main
thread of your program.
• Main thread is important for two reason:
 It is the thread from which other “child” threads will be created.
 It must be the last thread to finish execution because it performs various
shutdown actions.
• Main thread is created automatically when your program is started .it can be controlled
through a Thread object.
• We can refer that object by calling the method currentThread() which is public static
member of Thread.
Syntax: static Thread currentThread ( )
• This method returns reference to the thread in which it is called. If we have reference
to main thread, we can control it as any other thread.
• By default, the name main thread is main.
• Thread group is a data structure that controls the state of a collection of threads as a
whole. It is managed by the particular run-time environment.
Example: controlling the main Thread

By :Dhara Kanzariya Page 8


Chapter-7 Multithreaded Programming

class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t =Thread. currentThread ( );
System.out.println (“Current thread:”+ t);
t. setName (“Mythread”);
System.out.println (“After name change:” + t);
t. setPriority(10);
System.out.println (“After Priority set:” + t);
try
{
for(int n=5; n>0 ;n--)
{
System.out.println (n);
Thread. sleep (1000);
}
}
catch (InterruptedException e)
{
System.out.println (“Main thread interrupted “);
}
}
}
Output: Current thread: Thread [main, 5, main]
After name change: Thread [My Thread, 5, main]
After Priority set: Thread [My Thread, 10, main]
5
4
3
2
1

Thread class methods:


Thread encapsulates a thread of execution. Thread class defines several methods that help manage
threads.
No. Method Meaning
1 getName( ) Obtain a thread’s name.

By :Dhara Kanzariya Page 9


Chapter-7 Multithreaded Programming

2 setName( ) Set a thread’s name.


3 getPriority( ) Obtain a thread’s priority
4 setPriority( ) Set a thread’s priority
5 isAlive( ) Determine if a thread is still running.
6 join( ) Wait for a thread to terminate.
7 run( ) Entry point for the thread.
8 sleep( ) Suspend a thread for a period of time.
9 start( ) Start a thread by calling run method
Creating a thread
• We can create a thread by instantiating an object of type Thread.
• The run () method is the heart and soul of any thread.
• run( ) method makes up the entire body of a thread and is the only method in which
the thread’s behaviour can be implemented.
Syntax: public void run( )
{…………
………… // (statement for implementing thread)
}
The run ( ) method should be invoked by an object of concerned thread. For that we have
to create thread and initiate it with the help of other thread method called start ().
Java can create a thread by following two ways:
 You can implement the Runnable interface.
 You can extend the Thread class.
• Which one of above us should use?
The thread class defines several methods that can be overridden by a derived class .but
only one must be overridden is run ( ).
This is, the same method required when we implement Runnable.
Many Java programmers feel that classes should be extended only when they are being
enhanced or modified in some way. So it is probably best to implement Runnable instead of
extend Thread class.

Implementing the ‘Runnable’ interface


The Runnable interface declares the run ( ) method that is required for implementing threads
in our programs.
Steps to implement Runnable interface:

By :Dhara Kanzariya Page 10


Chapter-7 Multithreaded Programming

1. Declare the class as implementing the Runnable interface.


2. Implement the run ( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable”
class as the target of the thread.
4. Call the thread’s start( ) method to run the thread

Example of thread creation by implementing Runnable Interface:


class X implements Runnable //step1
{
public void run( ) //step2
{
for (int i=0; i<=10; i++)
{
System.out.println (“\t ThreadX:” + i );
}
System.out.println (“End of ThreadX”);
}
}
class RunnableTest
{
public static void main (String args[])
{
X obj =new X ( );
Thread t1= new Thread (obj); //step3
t1.start ( ); // step4
System.out.println (“End of main Thread”);
}
}
Output: End of main Thread
ThreadX: 1
ThreadX: 2
ThreadX: 3
ThreadX: 4
ThreadX: 5
ThreadX: 6
ThreadX: 7
ThreadX: 8
ThreadX: 9
ThreadX: 10
End of ThreadX

By :Dhara Kanzariya Page 11


Chapter-7 Multithreaded Programming

Extending the thread class

The Thread class declares the run ( ) method that is required for overriding threads in
our programs.
We can make our class runnable by extending the class java.lang.Thread.
To extend Thread class, perform following steps:
1. Declare the class as extending the Thread class.
2. Implement the run ( ) method that is responsible for executing the sequence of code
that the thread will execute.
3. Create a thread object and call the start ( ) method to initiate the thread execution .
Step 1: Declaring the class
Thread class can be extended as follows:
class MyThread extends Thread
{
………..
………..
} now we have new type of thread MyThread.
Step 2: Implementing the run ( ) interface
The run ( ) method has been inherited by the class MyThread. We have
overridden this method to implement the code executed by our thread.
public void run( )
{
……….. //Thread code here
}
When we start the new thread, java calls the thread’s run ( ) method, so it
is the run ( ) where all the actions takes place.
Step3: starting new thread
To actually create and run an instance of our thread class, we must write:
MyThread aThread =new MyThread ( );
aThread .start( ); // invokes run() method
Or
new MyThread( ).start ( );

• First line instantiate a new object of class MyThread.


It will just create object, the thread that will run this object is not yet running.
The thread is in newborn state.
• Second line calls the start ( ) method causing the thread to move into
runnable state.

By :Dhara Kanzariya Page 12


Chapter-7 Multithreaded Programming

Then java runtime will schedule the thread to run by invoking its run ( ) method,
Now thread is said to be in the running state.

Example of thread creation by extending Thread class:


class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\tFrom Thread A : i = " +i);
}
System.out.println("Exit From A");
}
}
class SingleThread
{
public static void main(String args[ ])
{
A thread1=new A( );
thread1.start ( );
//new A ( ).start( );
}
}
Output: From Thread A: i = 1
From Thread A : i = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread A : i = 5
Exit from A

Example: Write a program to create multiple threads.


class A extends Thread //step1
{
public void run ( ) //step2
{
for (int i=1; i<=5;i++)
{
System.out.println (“\t from Thread A: i =”+i);
}
System.out.println (“Exit from A”);

By :Dhara Kanzariya Page 13


Chapter-7 Multithreaded Programming

}
class B extends Thread
{
public void run( )
{
for (int j=1; j<=5;j++)
{
System.out.println (“\t from Thread B: j =”+j);
}
System.out.println (“Exit from B”);
}
class C extends Thread
{
public void run()
{
for (int k=1; k<=5;k++)
{
System.out.println (“\t from Thread C: k =”+k);
}
System.out.println (“Exit from C”);
}
class ThreadTest
{
public static void main(String args[])
{
new A( ).start(); //step3
new B( ).start();
new C( ).start();
}
}
Output:
First run
From Thread A : i = 1
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 3
From Thread C : k = 4

By :Dhara Kanzariya Page 14


Chapter-7 Multithreaded Programming

From Thread A : i = 5
Exit form A
From Thread B : j = 5
Exit from B
From Thread C :k = 5
Exit from C

Second run From Thread A : i = 1


From Thread A : i = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit form A
From Thread B : j = 3
From Thread B : j = 4
From Thread C :k = 5
Exit from C
From Thread B : j = 5

Exit from B

By :Dhara Kanzariya Page 15


Using isAlive ( ) and join( ) methods

In Multi-threading, one thread can know when another thread has ended or not by
using two methods isAlive ( ) and join ( ) method.
1) isAlive() :
• We can know state of any thread by these methods.
• This method is defined by Thread class .its general form is :
final boolean isAlive ( )
It returns true if the thread upon which it is called is still running, It returns false
otherwise.This method is occasionally useful.

2) Join() :

• The join method causes the current thread to wait until the thread upon which the join ( )
method is call, gets terminates.
• It s name comes from the concept of calling thread waiting until the specified thread
joins it.
• join ( ) also allows to specify a maximum amount of time that user want to wait for the
specified thread to terminate.
• This method is defined by Thread class .its general form is :
final void join( ) throws InterruptedException
Where the join () method either suspends the current thread for timeout
milliseconds or until the thread it calls on terminates.
• This method is commonly used.
Example of isAlive ( ) and join ( )

class display implements Runnable


{
public void run( )
{
int i=0;
while (i<4)
System.out.println (“Hello” + i ++);
}
}
Class Alivejoin_Demo
{
public static void main(String args[])
{
display d=new display();
Thread t1=new Thread(d);
Thread t2=new Thread(d);
Thread t3=new Thread(d);

t1.start ( );
t2.start ( );
t3.start ( );
try
{
System.out.println (“Thread t1 is alive:” + t1.isAlive ( ));
System.out.println (“Waiting for finishing threads t1”);

// following line causes main thread to wait until t1 terminate


t1.join ( );
System.out.println (“Thread t1 is alive:” + t1.isAlive ( ));
}
catch (InterruptedException e)
{
System.out.println (“thread t1 is interrupted “);
}
}
}
Output: Thread t1 is Alive :true
Hello : 0
Hello : 0
Hello : 0
Waiting for finishing thread t1
Hello : 1
Hello : 1
Hello : 1
Hello : 2
Hello : 2
Hello : 2
Hello : 3
Hello : 3
Hello : 3
Thread t1 is Alive: false
Threaded priority

• Every thread in java has its own priority.


• Thread priority are used by thread scheduler to decide when each thread should be
allowed to run.
• In theory, higher priority threads get more CPU time than lower priority threads.
• When a lower priority thread is running higher priority thread resumes (from
sleeping or waiting for on I/O), it will preempt the lower priority thread.
• Threads of equal priority should get equal access to the CPU. For this, thread that
share the same priority should yield control once in while.
• Every new thread that has created, inherits the priority of the thread that creates it.
• The priority is an integer value.Priority is in the range of 0 to 10.
( Thread.MAX_PRIORITY(0) to Thread.MAX_PRIORITY( 10 ) )
• To return thread to default priority ,specify NORM_PRIORITY (5) .
• These priorities are defined as final variables within Thread.
• If the value is out of this range than the method throws an exception
IllegalArgumentException.
• Most user level processes should use NORM_PRIORITY ,+1 OR -1
• Background tasks such as Network I/O and screen repainting should use a value very
near to lower limit.
• We should be very careful when trying to use very higher priority values.
• By assigning priorities to threads, we can ensure that they are given the attention they
deserve.
• Whenever multiple threads are ready for execution, the java system chooses the highest
priority thread and executes it. For a thread of lower priority to gain control ,one of the
following thing should be happen:
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().
If another higher priority thread comes along, the currently running thread will be preempted
by the incoming thread and move it to the runnable state.
Example
class A extends Thread
{
public void run( )
{
System.out.println(“threadA started”);
for ( int i=1; i<=4 ;i++)
{
System.out.println(“\t From thread A : i“+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
System.out.println(“threadB started”);
for ( int j=1; j<=4 ;j++)
{
System.out.println(“\t From thread B : j“+j);
}

System.out.println(“Exit from B”);


}
}
class C extends Thread
{
public void run()
{
System.out.println(“threadB started”);
for ( int k=1; k<=4 ;k++)
{
System.out.println(“\t From thread C: k“+k);
}
System.out.println(“Exit from C”);
}
}

class ThreadPriority
{
public static void main(String args[])
{
A t1=new A ( );
B t2=new B ( );
C t3=new C ( );

t3.setPriority (Thread.MAX_PRIORITY); //priority will be 10


t2.setPriority (t1.getPriority ( ) + 1); //priority will be 5
t1.setPriority (Thread.MAX_PRIORITY); //priority will be 6

System.out.println (“start thread A”);


t1.start ( );
System.out.println (“start thread B”);
t2.start ( );
System.out.println (“start thread C”);
t3.start ( );
System.out.println (“End of main thread “);
}

Output:
Start thread A
Start thread B
Start thread C
threadB started
from thread B: j=1
from thread B: j=2
threadC started
from thread C: j=1
from thread C: j=2
from thread C: j=3
from thread C: j=4
Exit from C
End of main thread
from thread B: j=3
from thread B: j=4
Exit from B
threadA started
from thread A:i=1
from thread A: i=2
from thread A: i=3
from thread A: i=4
Exit from A

Thread Exception
• The call to sleep ( ) method should enclosed in a try block and followed by a catch
block. This is necessary because the sleep ( ) method throws an exception, which
should be caught.
• Java run system will throw IllegalThreadStateException whenever we attempt to
invoke a method that a thread cannot handle in the given state.
Ex: sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions.
• Whenever we call a thread that may throw an exception, we have to supply appropriate
exception handler to catch it.
• Here ,the example of different Exception in multithreading are given in next slide:
catch (ThreadDeath e)
{
………………
……………… //Killed threads
}
catch( InterruptedException e)
{
……………… //cannot handles it in the current state
………………
}
catch (IllegalArgumentException e)
{
……………… //illegal method argument
………………
}
catch (Exception e)
{
………………
………………
}

Synchronization
• When two or more threads need to access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process of
achieving this is called synchronization.
For example, one thread may try to read a record from a file while another is
still writing to the same file. Depending on situation we may get strange result. We can
avoid this by synchronization.
• Monitor (semaphore) concept is key to synchronization.
• Monitor is an object that is used as a mutually exclusive lock or mutex.
• Only one thread can own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the monitor. Monitor is like a
key and the thread that holds the key can only open the lock.
• All the other threads attempting to enter the locked monitor will be suspended until the
first thread exists the monitor. This other threads are said to be waiting for the monitor.

• We can synchronize code in two ways:


1) Using synchronized Methods
2) The synchronized statement

Using synchronized methods


• To create object’s monitor, just call a method that uses synchronized keyword.
• While we declare a method with synchronized.java creates monitor and hands it over to
the thread that calls the method first time. While a thread is inside a synchronized
method, all other threads that try to call it on the same instance have to wait.
synchronized void method-name ( )
{
// code here is synchronized
}
• Whenever thread has completed its work of using synchronized method(or block or
code) ,it will hand over the monitor to the next thread that is ready to use the same
resource.
class Callme
{
synchronized void call(String msg)
{
System.out.print( " [ " + msg);
try
{
Thread. sleep (1000);
}
catch(InterruptedException e)
{
System.out.println("thread is interrupted");
}
System.out.print(" ] ");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
//synchronize calls to call()
public void run()
{
target.call(msg);
}
}
class Threadsynchro
{
public static void main(String args[])
{
Callme target =new Callme();
Caller ob1=new Caller(target,” hello");
Caller ob2=new Caller(target,"synchronized");
Caller ob3=new Caller(target,"world");
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
• Output:
[Hello] [World] [Synchronized]

 without synchronization block


[ Hello [world [synchronized ] ] ]

The synchronized statement


• Creating synchronized methods within classes that you create will not work in all
cases.
• For example, if you want to synchronize access to objects of a class that was not
designed for multithreading access means that class does not use synchronized
methods. In addition if this class was created by a third party and you don’t have
access to the source code .thus you can’t add synchronized to that class.
• To access a synchronized object of this class, we can use synchronized block by
putting calling method of a class in that block.
synchronized (lock-object)
{
// statements to be synchronized
}
• Here, lock-object is a reference to the object being synchronized.
• A synchronized block ensures that a call to a method that is a member of lock-object
occurs only after the current thread has successfully entered lock-object’s monitor.
Example
class Callme
{
void call(String msg)
{
System.out.print( " [ " + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("thread is interrupted");
}
System.out.print(" ] ");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
//synchronize calls to call()
public void run()
{
synchronized (target)
{
target.call(msg);
}
}
}
class Threadsynchro
{
public static void main(String args[])
{
Callme target =new Callme();
Caller ob1=new Caller(target,"hello");
Caller ob2=new Caller(target,"synchronized");
Caller ob3=new Caller(target,"world");
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
Output:
[ Hello ] [world] [Synchronized]
Output without synchronization block
[ Hello [world [synchronized ] ] ]

Dead lock
• When two or more threads are waiting to gain control of a resources which are already
hold by another waiting threads, and no one can further proceed, such situation is
known as deadlock.
Ex:
Thread A: synchronized method2()
{
synchronized method1()
{
……………..
}
}
Thread B: synchronized method1()
{
synchronized method2()
{
……………..
}
}

Interthread communication
• Polling is used to check some condition repeatedly. Once the condition is true
appropriate action is taken.
• In polling system, consumer would waste many CPU cycles, while it waited for the
producer to produce. Once producer complete it waits for to complete consumer to
finish.
• To avoid polling, Java includes inter process communication mechanism via the wait
(), notify( ) and notifyAll ( ) methods.
• These methods are implemented as final methods in object. (in package
java.lang.Object)
• All three methods can be called only from within a synchronized context.
1. Wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify().
Syntax: final void wait () throws InterruptedException
2. notify() wakes up the first thread that called wait () on the same object.
Syntax: final void notify()
3. notifyAll() wakes up all the threads that called wait() on the same object. The highest
priority thread will run fast.
Syntax : final void notifyAll()
Suspending, resuming & stopping threads
1. Stopping a thread :stop()
syntax : threadName.stop();
This causes the thread to move to dead state.A thread will also move to the dead
state automatically when it reaches the end of its method.
• The stop( ) method may be used when the premature death of a read is desired.
2. Resuming thread
syntax : threadName.resume();
• This causes the thread to move to runnable state.A thread will also move to the dead
state automatically in certain situation.
3. Suspending thread :sleep() ,wait() and suspend()
This all causes the thread to move to Blocked state
• threadName.sleep(t); This makes thread to sleep for t time (in milisecond),
after time elapsed thread will goes into runnable state.
• threadName.wait(); This tells thread to wait for some event to complete, to
gain control notify() method is called of that thread.
• threadName.suspend(); This suspends thread for some reason and then using
resume () method thread goes into runnable state.

---------------------------------------*--------------------------------------

You might also like