PMCA502L Java Programming
Module 2: Multithreading
Thilagavathi M, AP(Sr.), SCORE
Process
Any program under execution.
Thilagavathi M, AP(Sr.), SCORE
Multiprocessing
The capability to execute multiple processes at the same time.
This is termed as concurrency.
In a multiprocessor environment, each process may execute one
process and thus multiple processes may be executed
concurrently.
Running several processes at the same time (concurrently) in a
multiprocessor environment is referred to as physical concurrency.
(eg) Listening to music using VLC player & editing the MS word
document, at the same time.
Thilagavathi M, AP(Sr.), SCORE
Multiprogramming
How is concurrency achieved in a Uniprocessor Environment?
Thilagavathi M, AP(Sr.), SCORE
Logical Concurrency
The frequent context switching between the processes to keep
the CPU busy always, may appear as if multiple processes are
executed concurrently, although they are not executed at the
same time, in reality.
Thilagavathi M, AP(Sr.), SCORE
Multithreading
What is a thread?
A thread is a light weight process.
Thus thread-based multitasking will be more efficient than
process-based multitasking.
In process-based multitasking, multiple processes are executed at the same
time.
In thread-based multitasking, if a single process contains 2 or more portions
that can be run concurrently, then each portion is called a thread and all the
threads can execute concurrently (logical or physical concurrency).
Executing multiple threads of the same program concurrently is
also called multithreaded programming.
Java supports multithreaded Programming.
Thilagavathi M, AP(Sr.), SCORE
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete
life cycle of a thread.
Thilagavathi M, AP(Sr.), SCORE
Life Cycle of a Thread
Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
Runnable − A thread, that is ready to run is then moved to the runnable
state.
Running: When the thread gets the CPU, it moves from the runnable to the
running state.
Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions back
to the runnable state only when another thread signals the waiting thread to
continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thilagavathi M, AP(Sr.), SCORE
How is multithreaded programming supported in Java?
Two or more threads can be spawned (created) from within the
same program and all these threads can be made to execute
simultaneously.
Creation of thread:
Thilagavathi M, AP(Sr.), SCORE
Implementing the Runnable Interface
Define a class implementing the Runnable Interface and define the
run( ) method within this class.
Syntax: public void run( )
The class should define the run( ) method as a public member.
run( ) method is the entry point for a new thread that is created. The thread
will end when run( ) method returns. This method is not called by the JVM,
when it is started, using the java command. It must be invoked by the start( )
method. Therefore, all the threads which have been created, can execute
that piece of code included within the run( ) method simultaneously.
ii) Syntax: void start( )
It tells the JVM that the thread is ready for execution. Then the thread waits
until it is called by the scheduler. When the thread is called, the run( )
method is invoked.
Thilagavathi M, AP(Sr.), SCORE
Implementing the Runnable Interface
iii) Syntax: static currentThread( )
It returns a reference to the currently executing thread object which includes
the name of the currently running thread,
priority and
the group it belongs to
If the thread is not assigned any priority, explicitly, then the default priority
value 5 is assigned to it.
There are 3 constants representing the minimum priority, default priority and
the maximum priority, which can be assigned to a thread. They are:
Similarly, if names are not provided to the threads being created, default
names are assigned for those threads (Thread-0, Thread-1, and so on).
The thread group by default is 'main' unless it is explicitly created.
Thilagavathi M, AP(Sr.), SCORE
Write a program to create 2 threads by implementing Runnable interface. The 2
threads must display the message "Hello" along with their thread name, priority and
group. class
Thilagavathi M, AP(Sr.), SCORE
Output
Thread[main, 5, main]
Thread[Thread-0, 5, main]
Thread[Thread-1, 5, main]
Thilagavathi M, AP(Sr.), SCORE
The above program can be modified to pass, the object of the class implementing Runnable, to that
class constructor where the Thread object is created &start( ) method is invoked. This avoids writing the
'start( )' statement several times, each time for 1 thread.
Thilagavathi M, AP(Sr.), SCORE
Thread Methods
Sr.No Method & Description
.
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked
on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void join( )
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until
the second thread terminates or the specified number of milliseconds passes.
6 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it
runs to completion.
Thilagavathi M, AP(Sr.), SCORE
Static Methods of Thread Class
Sr.No. Method & Description
1 public static void yield()
Causes the currently running thread to yield to any other threads of the same
priority that are waiting to be scheduled.
2 public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number
of milliseconds.
3 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that
invokes this method.
Thilagavathi M, AP(Sr.), SCORE
Extending the Thread Class
Create a class by extending the Thread class. Define the run( ) method within
it, to include the code which should be run in parallel.
While creating thread object, do not create object for the Thread class but
create object for the new class that has been created by extending Thread
class.
Thilagavathi M, AP(Sr.), SCORE
Extending the Thread Class
Thilagavathi M, AP(Sr.), SCORE
Note:
The join( ) and sleep( ) methods throw an InterruptedException if the thread
is interrupted during its sleep state or waiting state.
So, they should be used within a try-catch block or at least the Exception
should be forwarded using 'Throws' clause.
try try
Thilagavathi M, AP(Sr.), SCORE