0% found this document useful (0 votes)
1 views

chapter 4-Multithreaded Programming (1)

The document provides an overview of multithreaded programming, particularly in Java, explaining concepts such as threads, their life cycle, and methods for creating and managing threads. It details the process of creating threads by extending the Thread class or implementing the Runnable interface, as well as discussing thread states, exceptions, priorities, and synchronization. Additionally, it covers inter-thread communication and provides example programs to illustrate these concepts.

Uploaded by

karpevaishnavi08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

chapter 4-Multithreaded Programming (1)

The document provides an overview of multithreaded programming, particularly in Java, explaining concepts such as threads, their life cycle, and methods for creating and managing threads. It details the process of creating threads by extending the Thread class or implementing the Runnable interface, as well as discussing thread states, exceptions, priorities, and synchronization. Additionally, it covers inter-thread communication and provides example programs to illustrate these concepts.

Uploaded by

karpevaishnavi08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Multithreaded Programming

Introduction

Almost all the modern operating systems support facility of multitasking.


Multitasking is achieved in two ways – process-based and thread based. Process
is defined as an instance of a program. In other words, program in execution is
called process. So, process-based multitasking provides facility of running
multiple programs concurrently.

Thread
Thread is a lightweight components and it is a flow of control. In other words
a flow of control is known as thread.

In thread-based multitasking, a program is divided into smaller subprograms


(threads), which may run concurrently. This results in greater level of
multitasking. Java also supports multithreading.
Generally a java program has a single flow of control. Such java program runs
sequentially. This type of program is called single-threaded program.

Multithreading in Java
Multithreading in java is a process of executing multiple threads
simultaneously. The aim of multithreading is to achieve the concurrent
execution.

A single java program may be divided into smaller subprograms as discussed


previously. This results in multiple flows of control. Such program having
multiple flows of control is called as multithreaded program. Figure 4.4 shows
four threads – one main and three other threads. The other three threads are
started by main thread. All these four threads run concurrently.
4.2.1 Creating a thread

Threads can be created in two ways.

– By extending the Thread class (extends)

-- By implementing the Runnable interface(implements)

4.2.1.1 Creating a thread by extending Thread class

For creating thread by extending Thread class, following steps need to be


followed. An example is also mentioned with each

step. 1. Declare a class that extends Thread class.

class MyThread extends Thread

--

}
Step 2. Override run( ) method of Thread class in the above class. Write the
code which is to be executed by the newly created thread in the run( )
method.

class MyThread extends Thread

public void run( )

//code to be executed by thread

Step 3. Create an object for the above class and call start( ) method for the
created object.

(One can call the start( ) method in the constructor of newly created class for
invoking the run( ) method automatically on creation of object of this class)

MyThread mt = new MyThread( );

mt.start( ); //run( )method gets invoked automatically

4.2.2 Life Cycle of Thread

From creation of thread to its termination, thread follows a cycle known as life
cycle of thread. It is shown in figure 4.5.

1) Newborn State or Initialize


2) Runnable
3) Running
4) Blocked
5) Dead
Various states through which a thread goes are discussed here. Also various
methods related to threads are also discussed.

Newborn State:

On creation, a thread enters in Newborn state. In this state Thread can call two
methods

Newborn State
start() stop()

Runnable Dead State


State

1) start( ) method to become active. On calling start( ) method, run( )


method of the thread is invoked automatically and it moves the thread
into runnable state.
2) And the second method call by Thread in this state is stop( ) method to
enter in Dead state.
Runnable State:

Multiple threads may be in Runnable state. The threads in this state are ready
for execution and are waiting for availability of processor. (Processor can run
only one thread at an instance). Selection of a thread for allocation of processor
may be done on the basis of priority of the threads. If threads are having same
priority, threads may get selected on First Come First Serve basis.

Running State:

There can be only one thread in Running state at given instance of time.
Processor is allocated to such thread and it is being run by processor. Running
thread may invoke yield( ) method for giving control to another thread. On
invoking suspend( ) method, thread gets suspended. On invoking sleep(time)
method, thread sleeps for specified number of milliseconds. On invoking wait( )
method, threads goes in waiting. In all these cases, thread enters in Blocked
state.

Queue Formed by Thread

A B C D

Yield()
Running Thread Runnable Thread

sleep(time)

Running Suspend()
Blocked
State State

wait()

Blocked State:

When thread is prevented from entering in Runnable state, it is in Blocked state.


There are various reasons for entering this state. Thread may be suspended,
sleeping or waiting for being in this state. Suspended thread may reenter in
active state by invoking resume( ) method. Sleeping state will automatically
enter in active state on completion of sleeping time. Waiting state may reenter
in active state by invoking notify( ) method. Newborn Dead start( ) stop( )
suspend( ) sleep( ) wait( ) resume( ) after specified time notify( ) stop( )
Blocked Active thread Running Runnable yield( ) ) stop( )

wait()
Runnable Blocked
State state
notify()

suspend()
Runnable Blocked
State resume() state

sleep()
Runnable Blocked
State state

Dead State:

Thread may enter this state on its natural death. Thread in any state may invoke
stop( ) method for entering in this state.
4.2.3 Thread Exceptions

From creation of thread to its termination, thread follows a cycle known as life
cycle of thread. It is shown in figure 4.5. It is also discussed previously that
various methods may be invoked by threads depending on their state. If a thread
tries to invoke a method which cannot be handled in the current state of that
thread, IllegalThreadStateException is thrown.

Example 1:

A sleeping thread cannot receive any instructions. So it cannot deal with a


method like resume( ).

Example 2: A blocked thread cannot handle suspend( ) method.

InterruptedException is thrown when a sleeping or waiting thread is interrupted.

Various other exceptions related to threads are ThreadDeath,


IllegalArgumentException etc.

4.2.4 Thread Priority

As at a particular instance of time, there may be multiple threads in the system,


we may assign priorities to the threads.

In a multithreading environment, there may be multiple threads which are


runnable. In such situation the priorities of the threads help in selecting the
threads for running. If multiple runnable threads have same priority, the threads
are selected on First Come First Serve basis.

We may assign a priority to a thread by using setPriority( ) method of thread


class . The syntax of this method is as follows

threadname.setPriority(intvalue);

Here intvalue is an integer value.

This value may be set with the help of different priority constants available
with Thread class.

Different priority constants of thread class are:


MIN_PRIORITY = 1

NORM_PRIORITY = 5 (This is default priority of every thread)

MAX_PRIORITY = 10

Generally priority of Thread.NORM_PRIORITY ± 1 is assigned to userdefined


threads. Background threads must be assigned with priority near to
MIN_PRIORITY. A programmer must take atmost care while assigning
priorities to threads.

Thread class also supports a getPriority( ) method which returns current priority
value of the thread.

When a high priority thread enters in runnable state while a low priority thread
is in running state, the running thread gets preempted. i.e. the low priority
running threads stops its execution by entering runnable state and the new high
priority thread starts its running by entering running state. This concept is called
preemption. An example program showing preemption is shown below.

class Thread1 extends Thread


{
public void run( )
{
int i;
for(i=0;i<10;i++)
{
System.out.println("In thread 1, i = " +i);
}
System.out.println("Exiting Thread 1");
}
}
class Thread2 extends Thread
{
public void run( )
{
int j;
for(j=0;j<10;j++)
{
System.out.println("In thread 2, j = "+j);
}
System.out.println("Exiting Thread 2");
}
}
class Thread3 extends Thread
{
public void run( )
{
int k;
for(k=0;k<10;k++)
{
System.out.println("In thread 3, k = "+k);
}
System.out.println("Exiting Thread 3");
}
}
class ThreadEx2
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );
t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread 1");
t1.start( );
System.out.println("Started Thread 2");
t2.start( );
System.out.println("Started Thread 3");
t3.start( );
System.out.println("Exiting main thread");
}
}
4.2.5 Synchronization
System may have multiple threads. Such threads may require communicating
with each other. In such case, if the communicating threads are not
synchronized, strange results may be produced. i.e. it may happen that the
shared method may get called by different threads at the same time. To avoid
this, the method may be marked keyword synchronized as,
synchronized returntype methodname(arglist)
{
----
}
Because of this, java creates a monitor. This monitor allows a thread calling this
method first time to execute that method. No any other thread is able to enter
this method as long as first thread is executing this method.

4.2.7 Inter-thread Communication

It involves exchange of messages between two or more threads. Java achieves


inter-thread communication with the help of various methods like notify( ),
notifyall( ), wait( ) etc.

notify( ) It resumes the first thread that went to sleep mode. Its syntax is as
follows
final void notify( )

notifyall( ) It resumes all the threads those are in sleep mode. Its syntax is as
follows
final void notifyall( )

wait( ) It sends the calling thread into sleep mode. This thread can come out of
sleep mode only by notify( ) method or notifyall( ) method. Its syntax is as
follows
final void wait( )

Creating Thread With Runnable Interface

For creating thread by implementing Runnable interface, following steps need


to be followed. An example is also mentioned with each

step. 1. Declare a class that implements Runnable interface.

class MyThread implements Runnable

--

2. Override run( ) method.

Write the code which is to be executed by the newly created thread in the run( )
method.
public void run( )

//code to be executed by thread

3. Create an object for the above class, Create Thread object by passing
the object just created as parameter to constructor and call start( ) method
for the thread object.

MyThread mt = new MyThread( );

Thread t = new Thread(mt);

t.start( ); //run( )method gets invoked automatically

An example program using this method is shown below.

Example:
class MyThread2 implements Runnable
{
public void run( )
{
int i;
System.out.println(“Starting MyThread2”);
for(i=10;i>=1;i--)
{
System.out.println(i*i*i); //Displays cubes from 10 to 1
}
System.out.println(“Exiting MyThread2”);
}
}
class RunnableEx3
{
public static void main(String[] args)
{
System.out.println(“Starting main thread”);
MyThread2 mt = new MyThread2( );
Thread t = new Thread(mt);
t.start( );
System.out.println(“Exiting main thread”);
}
}
Example : Write a program to discuss all the life cycle method of Thread
class

class Thread1 extends Thread


{
public void run( )
{
int i;
for(i=0;i<10;i++)
{
if(i==2)
{
yield( );
}
System.out.println("In thread 1, i = "+i);
}
System.out.println("Exiting Thread 1");
}
}
class Thread2 extends Thread
{
public void run( )
{
int j;
for(j=0;j<10;j++)
{
System.out.println("In thread 2, j = "+j);
if(j==5)
{
stop( );
}
}
System.out.println("Exiting Thread 2");
}
}
class Thread3 extends Thread
{
public void run( )
{
int k;
for(k=0;k<10;k++)
{
System.out.println("In thread 3, k = "+k);
if(k==1)
{
try
{
sleep(200);
System.out.println("Thread 3 sleeps for 200 milliseconds");
}
catch(Exception e)
{
}
}
}
System.out.println("Exiting Thread 3");
}
}
class ThreadEx4
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
Thread3 t3 = new Thread3( );
System.out.println("Started Thread 1");
t1.start( );
System.out.println("Started Thread 2");
t2.start( );
System.out.println("Started Thread 3");
t3.start( );
System.out.println("Exiting main thread");
}
}

You might also like