You are on page 1of 40

MODULE - IV

Multithreaded
Programming
MODULE 4

Multithreaded Programming
Module Description

Java is a multithreaded programming language. It contains two or more paths that can
simultaneously run and handle the different task at the same time. It is used to share the
available resource optimally and enfolds when a user has multiple CPUs. It also share common
processing resource such as CPU and subdivide specific operations within a single application
into individual threads where each threads can run in parallel.

The thread is a programme's path of execution. In Java, the word thread means two things
which are different. Most programmes written today run as a single thread, causing problems
when multiple events or actions need to occur at the same time. Let's say, for example, a
programme is not capable of drawing pictures while reading keystrokes. To manage such
situations, the programmers designed Java as a multithreaded programming language which
means we can develop a multithreaded programme using Java. It enhances the speed and
improves responsively of an application.

This module deals with thread lifecycle, thread priorities, synchronisation, main threads,
creating multiple threads and inter-thread communication.

By the end of this course, students will be able to describe life cycle of a thread, develop a
program to create two threads and set priorities of thread, describe methods of thread and
differentiate between implementing runnable and extending thread.

iNurture’s Programming in Java course is designed to serve as a stepping stone for you to build
a career in Information Technology.

Chapter 4.1
Introduction to Threads

Chapter 4.2
Basic Input/Output and UI
Chapter Table of Contents
Chapter 4.1

Introduction to Threads
Aim ..................................................................................................................................................... 185
Instructional Objectives................................................................................................................... 185
Learning Outcomes .......................................................................................................................... 185
4.1.1 Introduction to Threads ......................................................................................................... 186
Self-assessment Questions ...................................................................................................... 187
4.1.2 Java Thread Model .................................................................................................................. 188
(i) Lifecycle of a Thread .......................................................................................................... 188
(ii) Thread Priorities ............................................................................................................... 190
(iii) Synchronisation ............................................................................................................... 191
(iv) Thread Class...................................................................................................................... 191
(v) Runnable Interface ............................................................................................................ 193
Self-assessment Questions ...................................................................................................... 194
4.1.3 The Main Thread .................................................................................................................... 195
Self-assessment Questions ...................................................................................................... 197
4.1.4 Creating Threads ..................................................................................................................... 197
(i) Implementing Runnable.................................................................................................... 197
(ii) Extending Thread.............................................................................................................. 199
(iii) Creating Multiple Thread ............................................................................................... 201
(iv) isAlive( ) and Join( ) Methods ........................................................................................ 203
Self-assessment Questions ...................................................................................................... 205
4.1.5 Thread Priorities ..................................................................................................................... 206
Self-assessment Questions ...................................................................................................... 207
4.1.6 Thread Synchronisation ......................................................................................................... 208
(i) Inter Thread Communication .......................................................................................... 208
(ii) Suspending, Resuming and Stopping Threads .............................................................. 209
Self-assessment Questions ...................................................................................................... 213
Summary ........................................................................................................................................... 214
Terminal Questions.......................................................................................................................... 214
Answer Keys...................................................................................................................................... 215
Activity............................................................................................................................................... 216
Bibliography ...................................................................................................................................... 217
External Resources ........................................................................................................................... 217
Video Links ....................................................................................................................................... 217
Aim
To provide students with the basics of multithreaded programming

Instructional Objectives
After completing this chapter, you should be able to:

• Demonstrate Java thread model

• Illustrate thread implementation

• Create a thread by implementing Runnable interface

• Describe thread priorities

• Illustrate thread synchronisation

Learning Outcomes
At the end of this chapter, you are expected to:

• Describe life cycle of a thread

• Develop a program to create two threads, one thread will print odd numbers
and second thread will print even numbers between 1 to 20 numbers

• Develop a program to set priorities of thread

• Describe the methods of the thread class used to schedule the threads

• Differentiate between implementing runnable and extending thread

• List the advantage of multithreading

• Describe inter-thread communication

185
4.1.1 Introduction to Threads
Definition of Thread:

“Thread, in the circumstances of Java, is the path followed when executing a program or code.
Whole Java programs have at least one thread, known as the main thread, which is generated
by the Java Virtual Machine(JVM) at the program’s start, when the main( ) method is invoked
on the main thread. In Java, creating a thread is succeeded by implementing an interface and
extending a class. Every Java thread is built and controlled by the class named
"java.lang.Thread" ”.

When a thread is created, it is specified priority. The thread with higher priority is executed
first, followed by lower-priority threads. The JVM stops running threads under the following
conditions given below:

• If the exit method has been invoked and authorised by the security manager.

• Total daemon threads of the program have expired.

Multithreading:

A multithreaded program includes multiple parts that can run concurrently. Each part of such
a program is called a thread and each thread defines a separate path of execution. Thus,
multithreading is a specialised form of multitasking. You are almost certainly acquainted with
multitasking because it is supported by virtually all modern operating systems. However, there
are two distinct types of multitasking: process based and thread-based. It is necessary to
understand the different between the two. For most readers, process-based multitasking is the
most familiar form. A process is, in essence, a program that is executing. Thus, process-based
multitasking is the feature that allows your computer to run two or more programs
concurrently.

For example, process-based multitasking enables you to run the Java compiler at the same time
that you are using a text editor. In process based multitasking, a program is the smallest unit of
code that can be dispatched by the scheduler.

186
Benefits of Multithreading

• Enables the programmers to do multiple tasks at the same time.

• Increase the speed of program execution by dividing the program into threads and
execute them in parallel.

• Actions can be simultaneous across multiple application.

• It improves the performance and concurrency.

Self-assessment Questions
1) Identify which of the following process takes place in multithreaded programming
a) Process in which two different processes run simultaneously
b) Process in which two or more parts of same process run simultaneously
c) Process in which many different process are able to access same information
d) Process in which a single process can access information from many sources.

2) A thread can exist in several states.


a) True b) False

187
4.1.2 Java Thread Model
Multithreading is the main concept in Java programming. It has advanced features when
compared to the single-thread model. Java’s run-time system has been designed keeping a
multi-thread model in mind. Let’s see the life cycle of a thread.

(i) Lifecycle of a Thread


Threads can be one in five states. They are:

1. First State - New thread yet to start. -> When coder creates a new Thread object using
the new operator, thread state is New Thread. At this point, a thread is not alive and it’s
a state internal to Java programming.

2. Second State - Ready to run the state. It achieves through start ( ) method. -> When
we call to start ( ) function on Thread object, it states is changed to Runnable and the
control is given to Thread scheduler to terminate its execution. Whether to run this
thread instantly or keep it in runnable thread pool before moving it depends on the OS
implementation of thread scheduler.

3. Third State - Running state. -> When a thread is performing, it states is changed to
Running. Thread scheduler picks one of the thread from the runnable thread pool and
changes it's reported to Running and CPU starts performing this thread. A thread can
change state to Runnable, Dead or Blocked from running state depends on time slicing,
thread completion of run( ) method or waiting for some resources.

4. Forth State - Waiting/Blocked. -> A thread can be waiting for the different thread to
finish using thread join or it can be waiting for some resources to available, for
example, producer consumer problem or waiter notified implementation or IO
resources, suddenly its state is changed to Waiting. Once the thread wait state is over,
its state is changed to Runnable and it’s moved back to the runnable thread pool.

5. Final State - Dead state. -> Once the thread finished executing, its state is changed to
Dead and it’s considered to be not alive.

188
Figure 4.1.1: Thread Lifecycle

According to Sun Microsystems, there are only four states. That is, new, runnable and non-
runnable and terminated.

Let see an example of Thread States:

public class ThreadStates


{
private static Thread e1 = new Thread("E1")
{ // (1)
public void run()
{
try
{
sleep(2); // (2)
for(int p = 10000; p > 0; p--); // (3)
} catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
};
public static void main(String[] args)
{

189
e1.start();
while(true)
{ // (4)
Thread.State state = e1.getState();
System.out.println(state);
if (state == Thread.State.TERMINATED) break;
}
}
}

Possible output from the program:

RUNNABLE

TIMED_WAITING

...

TIMED_WAITING

RUNNABLE

...

RUNNABLE

TERMINATED

This above example illustrates changes between thread states. A thread at (1) (where a thread
is being started) sleeps a little at (2) and then does some estimate in a loop at (3), after that the
thread terminates. The main( ) monitors the thread in a loop at (4), printing the thread state
returned by the getState( ) method. The output reveals that the thread goes through the
RUNNABLE state when the run( ) starts to execute and then transits to the condition of
TIMED_WAITING state to sleep. On rising, it computes the loop in the RUNNABLE state and
transits to the TERMINATED state when the run( ) method finishes (or ends).

(ii) Thread Priorities


In Java, each thread has its priority to implement itself. It helps the operating system to
determine the order in which it has to be scheduled. When a thread moves from one running
state to next, then it will decide its priority (direction of its movement depends on its priority).
This process of navigating itself according to its priority is known as context switching.

The priorities of a thread range between MIN_PRIORITY and MAX_PRIORITY. These


priorities help to increase the running time of thread or execution time also.

190
(iii) Synchronisation
As multithreading introduces an asynchronous behaviour to your programs, there must be a
way for you to drive synchronicity when you require it.

For example, if you need two threads to communicate and share a complex data structure, such
as a linked list, you need some way to assure that they don’t differ with each other. That is, you
must prevent one thread from writing data while another thread is in the middle of reading it.
For this purpose, Java executes an elegant twist on an age-old model of interposes
synchronisation: the monitor. The monitor is a control mechanism first defined. You can think
of a screen as a tiny box that can hold only one thread. Once a thread enters a monitor, all other
threads must wait till that thread exits the monitor. In this way, a screen can be used to protect
a shared asset from being managed by more than one thread at a time.

(iv) Thread Class


Java’s multithreaded model is based on Thread class because it acts as a main class in the
multithreaded system. They are used to design and execute the multithreading features of Java
using Runnable interface.

Multithreaded features are utilised using Constructors of Thread classes. Some of them are:

1. Thread ( )

2. Thread (String str)

3. Thread (Runnable r)

4. Thread (Runnable r, String str)

191
Thread class defines methods for managing threads. Some of the methods are as follows:

Method Description

Method Description

setName( ) Naming a thread

getName( ) Return thread’s name

getPriority( ) Return’s thread’s priority

isAlive( ) Checks whether the thread is currently running or not

join( ) Wait for a thread to end

run( ) Entry point of a thread

sleep( ) Suspend the thread

start( ) Start a thread by calling run( ) method

Table 4.1.1: Methods of Thread Class

Thread Scheduling:

Most computer configurations have the only a CPU. Hence, threads run one at a time in such
a way as to provide an illusion of concurrency. Execution of more than one threads on a single
CPU in some order is called scheduling. The Java runtime environment supports a very
deterministic, simple scheduling algorithm called fixed-priority scheduling. This algorithm
schedule threads by their priority about other Runnable threads.

When a thread is built, it inherits its priority from the thread that created it. You also can
modify a thread’s priority at any time after its creation by using the set Priority method. Thread
priorities are integers ranging between MAX_PRIORITY and MIN_PRIORITY. The higher
the integer, the higher the priority. At any assigned time, when more than one threads are ready
to be executed, the runtime system select for execution the Runnable thread that has the highest
priority. Only when that thread stops, yields, or becomes Not Runnable will a lower-priority
thread start executing. If two threads of the likewise priority are waiting for the CPU, the
scheduler arbitrarily picks one of them to run. The chosen thread (or error) runs until one of
the following conditions is true:

• A leading priority thread becomes runnable.

192
• It allows, or its run method exits.

• On systems that hold time-slicing, its time allotment has expired.

Then the second thread is given a possibility to run and so on, until the editor exits.

Thread scheduling algorithm of the Java runtime system is also preemptive. If anytime a thread
with a higher priority than all other Runnable threads becomes Runnable, the runtime system
chooses the new higher-priority thread for execution. The current thread is said to preempt the
other threads.

(v) Runnable Interface


Thread class can create a thread by extending its object. But only one class can be extended; it
won’t allow multiple inheritances to take place. So to create many inheritances, a programmer
can create a thread by implementing Runnable interface.

Using Runnable interface, multiple inheritances implemented at the same time.

While implementing Runnable interface, a user need to provide an implementation of run( )


method.

Let’s look at the steps to be followed to implement Runnable Interface:

Step 1: Create a new thread; your program will unless extending Thread or execute the
Runnable interface.

Step 2: To start executing run( ) method, call start( ) method on Thread class.

Step 3: Implementing Runnable interface defines only an entry point for threads in the object,
it does not create a Thread object. Rather it allows the user to pass the object to the Thread
constructor (Runnable Implementation).

Here is an example program of main class starts the “first thread” and “second thread”:

public class MyThread


{
public static void main(String args[])
{
FirstThread f = new FirstThread(); // first thread//
SecondThread s = new SecondThread(); //second thread//
Thread thread1 = new Thread (f); thread1.start();
Thread thread2 = new Thread(s);

193
thread2.start();
}
}
Output:
Message of f: 1

Message of s: 1

Message of f: 2

Message of s: 2

Self-assessment Questions
3) To stop the execution of a thread, which of the following method is used?
a) notify b) wait( )
c) notifyall( ) d) stop( )

4) callingnotify( ) method directly stop the thread execution.


a) True b) False

5) Identify which two of the following methods are defined in class Thread?
1. start( )
2. wait( )
3. notify( )
4. run( )
5. terminate( )
a) 1 and 4 b) 2 and 3
c) 3 and 4 d) 2 and 4

6) A thread become non-runnable when stop( ) method is invoked.


a) True b) False

194
7) Identify two valid constructors to implement a Thread from the following?
1. Thread(Runnable r, String name)
2. Thread( )
3. Thread(int priority)
4. Thread (Runnable r, int priority)
a) 1 and 3 b) 2 and 4
c) 1 and 2 d) 2 and 3

8) ______________method is used to start a thread execution.


a) init( ); b) run( );
c) resume( ); d) start( );

4.1.3 The Main Thread


One thread begins running immediately when a Java program starts up. It is usually called the
main thread of your program because it is the one that is executed when your program begins.
The main thread is relevant for two reasons:

1. It is the thread from which other “child” threads will be spawned.

2. Often, it must be the last thread to finish execution because it performs several
shutdown actions.

Programmers can refer the main thread using CurrentThread( ) method. General form of the
main thread is

Static Thread currentThread( ); // used to return authority to the thread in which it is called.

Let’s begin by reviewing the following example:

// controlling the main Thread.


class CurrentThreadDemo
{
public static void main(String args[])
{
Thread x = Thread.currentThread();
System.out.println("Current thread: " + x);

195
// change the name of the thread
x.setName("My Thread");
System.out.println("After name change: " + x);
try
{
for( int i= 3; i > 0; i--)
{
System.out.println(i);
Thread.sleep(500);
}
} catch (InterruptedException e)
{
System.out.println("The main thread has interrupted");
}
}
}

In this preceding program, a source of the current thread is obtained by calling


currentThread( ) and this reference is stored in the local variable x. Next, the program displays
information about the thread. The program then calls setName( ) to change the internal name
of the thread. Information about the thread is then re-open. Next, a loop counts down from
five, pausing one second between each line. The pause is accomplished by the sleep( ). The
argument to sleep( ) method specifies the delay period in milliseconds. Notice the try/catch
block around this loop. The sleep( ) method in Thread might throw an InterruptedException.
It would happen if some other thread wanted to interrupt this sleeping/inactive one. This
example just prints a message if it gets suspended. In an original program, you would require
to handle this individually.

Here is the generated output by this program:

Current thread: Thread[main,3,main]

After name change: Thread[My Thread,3, main]

Notice the output produced when x is used as an argument to println( ).

196
Self-assessment Questions
9) Which of the following is a static member of Thread?
a) Join( ) b) getName( )
b) interrupt( ) d) currentThread()

10) Which of the following method is used for a thread to come out of its running state?
a) wait( ) b) notify( )
c) sleep( ) d) notifyall()

4.1.4 Creating Threads


The thread is processed in two ways. They can be achieved by

• Implementing Runnable Interface

• Extending the Thread class

In turn, the following two segments look at each method.

(i) Implementing Runnable


Implementing Runnable Interface is the simplest way of creating a class that implements the
Runnable interface. Java gives an opportunity to apply multiple interfaces at a time. To
implement Runnable a single method run ( ) is used.

By implementing the Runnable interface, it creates a Thread object within a class that defines
several constructor and pass Runnable implementation class object to its constructor.

a) Runnable interface:
• Create an object of the high class.

• Assign a thread object for the class thread.

• Call the method “start” on the assign thread object.

197
For example,

An example of Runnable interface that creates a new thread and starts it running, which is given
below:

// Create a second thread.


class NewThread implements Runnable
{
Thread x;
NewThread()
{
// Create a new, second thread
x= new Thread(this, "Demo Thread");
System.out.println("Child thread: " + x);
x.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int p= 5;p> 0; p--)
{
System.out.println("Child Thread: " + p);
Thread.sleep(400);
}
} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int p= 5; p> 0; p--)
{
System.out.println("Main Thread: " + p);
Thread.sleep(900);
}
} catch (InterruptedException e) {System.out.println(" The main
thread has interrupted.");}
System.out.println(The main thread is exiting.");
}
}

198
Within NewThread’s constructor, a new Thread object is created by the following statement:

x = new Thread(this, "Demo Thread");

Passing this as the first argument indicates that you want the new thread to call the run( )
method on this object. Next, start( ) is called, which starts the thread of execution beginning at
the run( ) method. It causes the child thread’s for loop to start. After calling start( ),

NewThread’s constructor responds to main( ). When the main thread continues, it enters its
for loop. Both threads resume running, sharing the CPU until their loops finish.

Output produced by this program is as follows.

Note: Your output may vary based on processor speed and task load.

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread.

Main Thread: 2

Main Thread: 1

The main thread is exiting.

(ii) Extending Thread


Extending thread is another way of creating a thread. It creates an instance of a new class that
extends Thread. To prolong a thread it has to override run( ) method. To start performing
thread object, start( ) method should be called.

199
For example,

Here is the above program rewritten to extend Thread:

// Create a second thread by extending Thread


class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int p= 5; p> 0; p--)
{
System.out.println("Child Thread: " + p);
Thread.sleep(400);
}
} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int p= 5; p> 0; p--)
{
System.out.println("Main Thread: " + p);
Thread.sleep(900);
}
} catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("The main thread is exiting.");
}
}

200
This program generates the same output as the preceding version. As you can see, the child
thread is created by instantiating an object of NewThread, which is derived from Thread.
Notice the call to super( ) inside NewThread. It invokes the following form of the Thread
constructor: public Thread(String threadName)

Here, threadName specifies the name of the thread.

(iii) Creating Multiple Thread


Multiple threads are created for the optimal use of memory resources and speed up the
execution time by dividing a task into multiple threads.

For an example, the following program creates three child threads for this code:

// Create multiple threads.


class NewThread implements Runnable
{
String name; // name of thread
Thread x;
NewThread(String threadname)
{
name = threadname;
x= new Thread(this, name);
System.out.println("New thread: " + x);
x.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int p= 5; p> 0; p--)
{
System.out.println(name + ": " + p);
Thread.sleep(900);
}
} catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " main exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads

201
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(9000);
} catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("The main thread is exiting.");
}
}

Output for this above program is shown here:

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.

202
Three exiting.
The main thread is exiting.

As you can observe, once started, all three child threads share the CPU. Notice the call to sleep
(9000) in main ( ). It causes the main thread to sleep for ten seconds and assures that it will
finish at last.

(iv) isAlive( ) and Join( ) Methods


All threads are interdependent with each other. One thread should know when another thread
is ending. In Java, there are two methods to check whether one thread has finished its execution
or not. The methods are:

1. isAlive( ) method

2. Join( ) method

isAlive( ) method tells the current status of a thread by returning a boolean value as True if the
specified thread which is called is still running. Otherwise, it returns False.

Syntax:
final Boolean isAlive( )

Join ( ) method waits till thread on which it is called is terminated. It is the most commonly
used method when compared to isAlive( ). It informs the other thread to wait until the specified
thread completes its execution.

Two methods/ways endure determining whether a thread has finished. First, the coder can call
isAlive( ) method on the thread. This method is defined by Thread and its general form is
shown here:

final boolean isAlive( ) The isAlive( ) method returns true if the thread upon which it is called
is still running. It returns false otherwise. While isAlive( ) is seldom useful, the method that you
will more commonly use to wait for a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException. This method remains pauses until the thread
on which it is called terminates.

203
Example of isAlive( ) method
public class FirstThread extends Thread
{
public void run( )
{
System.out.println("p1 ");
try
{
Thread.sleep(300);
}
catch (Interrupted Exception ie){ }
System.out.println ("p2 ");
}
public static void main(String[] args)
{
FirstThread k1=new FirstThread();
FirstThread k2=new FirstThread();
k1.start ( );
k2.start ( );
System.out.println (k1.isAlive ());
System.out.println (k2.isAlive ());
}
}
Output:
true
true
p1
p1
p2
p2
Example of join( ) method:
public class SecondThread extends Thread
{
public void run( )
{
System.out.println("p1 ");
try
{
Thread.sleep(500);
}
catch(InterruptedExceptionie){ }
System.out.println("p2 ");
}
public static void main(String[] args)
{

204
SecondThread k1=new SecondThread( );
SecondThread k2=new SecondThread();
k1.start ( );
try
{
k1.join ( ); //Waiting for k1 to finish
} catch (Interrupted Exception ie) { }
k2.start ( );
}
}
Output:
p1

p2

p1

p2

As you can observe, after the calls to join ( ) return, the threads have ended executing.

Self-assessment Questions
11) Which method must be defined by a class implementing the java.lang.RunnableI
interface?
a) Void run( ) b) public void run( )
c) public void start( ) d) void run(int priority)

12) Match the following?


a) run( ) creates a new thread
b) start( ) executes the current thread
c) stop( ) creates a child thread
d) main( ) stops a thread

205
4.1.5 Thread Priorities
All threads have priorities. They are indicated by a number between 1 and 10. The thread
scheduler schedules the thread according to their priority. The process of scheduling the
threads to its priority is known as Preemptive scheduling. They are dependent on Java Virtual
Machine, which chooses the schedule. The thread priorities are:

1. MIN_PRIORITY
2. MAX_PRIORITY
3. NORM_PRIORITY

As discussed in Thread methods, set Priority( ) and get Priority( ) methods are called by passing
an integer with their priorities which range between two constants MIN_PRIORITY and
MAX_PRIORITY defined on threads.

Default Priority of a Thread is 5(NORM_PRIORITY).

The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Problems with Thread Priorities

1. Priorities depend on the system’s OS and virtual memory. The thread method
Thread.setPriority( ) does not prioritisation while handling multiple events.

2. No priority is beyond the possible range. For example, thread handling an audio data pre-
empted by some random user thread.

3. The availability of priorities differs from system to system.

4. Manually manipulating a thread priority will interfere with the OS which in turn reduces
the speed of the system.

5. It is hard to predict the current status of a thread because the current running application
doesn’t know what threads are running in other processes.

Here is an example of thread priority

classTestMorePriority extends Thread


{
public void run( )
{

206
System.out.println("first running thread name
is:"+Thread.currentThread().getName());
System.out.println("another running thread priority
is:"+Thread.currentThread().getPriority());
}
}
public static void main(String[] args)
{
TestMorePriority p1=new TestMorePriority();
TestMorePriority p2=new TestMorePriority();
p1.setPriority(Thread.MIN_PRIORITY);
p2.setPriority(Thread.MAX_PRIORITY);
p1.start();
p2.start();
}

The output of this above program, shown as follows when running under Windows, indicates
that the threads did a context switch, even though neither voluntarily yielded the CPU nor
blocked for I/O. The higher-priority thread got the majority of the CPU time.

Output:
first running thread name is:

another running thread priority is:

first running thread name is:

another running thread priority is:

Of course, the accurate output produced by this program depends on the speed of your CPU
and the number of other tasks running in the system. When this same program is run under a
non-pre-emptive system, many results will be obtained.

Self-assessment Question
13) MIN_PRIORITY is the default priority of a newly created thread?
a) True b) False

207
4.1.6 Thread Synchronisation
When more than one thread tries to access a shared resource, the programmer needs to ensure
that only one thread will use the resource at a time. The process of allocating the resource for a
single thread at a time is known as Thread synchronisation.

Synchronised keyword is used to create a block of code called as a critical section. Every object
with a critical section of code gets a lock associated with the object.

Syntax:
Synchronised (object)
{
//Statement which is to be synchronised
}

(i) Inter Thread Communication


Inter thread communication is a process of making all synchronised threads to communicate
with each other. It is a mechanism by which, a thread delays in its critical section and another
thread is made to enter the same critical section to execute a task. It can be done through Object
methods ( ) such as:

• wait( )

• notify( )

• notifyAll( )

a) wait( ) method notify the called thread to give up the monitor and go to sleep until some
other thread calls notify( ).

b) notify( ) method wakes up the thread which already called wait( ) on the same object.

c) notifyAll( ) method wakes up all the thread that had called wait( ) method.

For example,
class Sid{}
class Sushil{}
public class Study
{
public static void main(String[] args)
{
final Sid sd =new Sid();
final Sushil sl =new Sushil();

208
Thread p1 = new Thread()
{
public void run()
{
synchronised (sd)
{
System.out.println("Thread1 is holding Sid");
Try
{
Thread.sleep(2000);
}catch(InterruptedException e) { }
synchronised(sl)
{
System.out.println("Requesting for Sushil");
}
}
}
Thread
};
Thread p2 = new Thread()
{
public void run()
{synchronised(sl)
{
System.out.println("Thread2 is holding Sushil");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
synchronised(sd)
{System.out.println("requesting for Sid"); }
}
}
};
p1.start();
p2.start();
}
}
Output:
Thread2 is holding Sushil

Thread1 is holding Sid

(ii) Suspending, Resuming and Stopping Threads


Suspending a Thread is a process of postponing a thread in suspended state and making it
resume later. It can be achieved using suspend( ) method.

209
Syntax - public void suspend( )

Resuming a Thread is a process of making a thread resume to its original running state after
suspending.

Syntax - public void resume( )

Stopping a Thread is a process of stopping a thread completely. It can be done using stop( )
method.

Syntax - public void stop( )

Here is an example for suspending, resuming and stopping a thread.

classRunnableDemo implements Runnable


{
public Thread t;
private String threadName;
boolean suspended = false;
RunnableDemo( String name)
{
threadName = name;
System.out.println ("Creating " + threadName );
}
public void run ( )
{
System.out.println("Running " + threadName );
try
{
for(int i = 10; i> 0; i--)
{
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(300);
synchronised (this)
{
while(suspended)
{
wait();
}
}
}
} catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

210
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
void suspend()
{
suspended = true;
}
synchronised void resume()
{
suspended = false;
notify();
}
}
public class FindThread
{
public static void main(String args[])
{
RunnableDemo R1 = new RunnableDemo("Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo(“Thread-2");
R2.start();
try
{
Thread.sleep(1000);
R1.suspend();
System.out.println("Suspending First Thread");
Thread.sleep(1000);
R1.resume();
System.out.println("Resuming First Thread");
R2.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
R2.resume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
try
{
System.out.println("Waiting for threads to finish.");
R1.t.join();
R2.t.join();
}
catch (InterruptedException e)

211
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

The output from this above program is shown here. (Your output can be differ based on
processor speed and task load.)

Output:
Creating Thread-1

Starting Thread-1

Creating Thread-2

Starting Thread-2

Running Thread-1

Thread: Thread-1, 10

Running Thread-2

Thread: Thread-2, 10

Thread: Thread-1, 9

Thread: Thread-2, 9

Thread: Thread-1, 8

Thread: Thread-2, 8

Thread: Thread-1, 7

Thread: Thread-2, 7

Suspending First Thread

Thread: Thread-2, 6

Thread: Thread-2, 5

Thread: Thread-2, 4

Resuming First Thread

Suspending thread Two

Thread: Thread-1, 6

212
Thread: Thread-1, 5

Thread: Thread-1, 4

Thread: Thread-1, 3

Resuming thread Two

Thread: Thread-2, 3

Waiting for threads to finish.

Thread: Thread-1, 2

Thread: Thread-2, 2

Thread: Thread-1, 1

Thread: Thread-2, 1

Thread Thread-1 exiting.

Thread Thread-2 exiting.

The thread class also describes a method called stop( ) that ends a thread. Its signature is shown
here:

final void stop( )

Once a thread has been stopped, it cannot be restarted using by resume( ) method.

Self-assessment Questions
14) Which of the following method will not directly cause a thread to stop?
a) wait( ) b) notify( )
c) sleep( ) d) InputStream access

15) Which class or interface defines the wait( ), notify( ) and notifyAll( ) methods?
a) Object b) Thread
c) Runnable d) Class

213
Summary
o Java is a multithreaded programming language. It contains two or more paths that
can simultaneously run and handle the different task at the same time.

o A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread and each thread defines a separate
path of execution.

o According to Sun Microsystems, there are only four states. That is, new, runnable
and non-runnable and terminated.

o Java’s multithreaded model is based on Thread class because it acts as middle class
in the multithreaded system.

o The thread scheduler schedules the thread according to their priority. The process
of scheduling the threads to its priority is known as Preemptive scheduling.

o Interthread communication is a process of making all synchronised threads to


communicate with each other.

Terminal Questions
1. Describe the life cycle of a thread.

2. List the advantages of multithreading

3. Describe inter-thread communication

214
Answer Keys
Self-assessment Questions
Question No. Answer

1 b
2 a
3 b
4 a
5 a
6 a
7 c
8 d
9 d
10 c
11 c
12 b, a, d, c
13 b
14 a
15 b

215
Activity
Activity Type: Online

Description:

Write java application program for generating four threads to perform the following
operations:

1. Getting ‘N’ numbers as input


2. Printing the even numbers
3. Printing the odd numbers
4. Computing the average

216
Bibliography

External Resources
• (2016). Retrieved 12 June 2016, from http://www.freejavaguide.com/java-threads-
tutorial.pdf

• (2016). Retrieved 12 June 2016, from


http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf

• (2016). Retrieved 12 June 2016, from https://www.fbi.h-


da.de/~a.schuette/Vorlesungen/ParallelProgramming/Skript/JavaThreads/JavaTh
reads.pdf

• (2016). Retrieved 12 June 2016, from


http://www.tutorialspoint.com/java/pdf/java_thread_synchronization.pdf

• The complete reference JAVA 7th edition/Herbert schildt.Publication-McGraHill

Video Links
Topic Link

http://www.uml-diagrams.org/examples/java-6-thread-
States of thread
state-machine-diagram-example.html

http://javarevisited.blogspot.in/2011/02/how-to-
Thread Implementation
implement-thread-in-java.html
https://www.youtube.com/watch?v=bwJdy5Y6d7w
Java Concurrency http://tutorials.jenkov.com/java-
concurrency/index.html

217
Notes:

218

You might also like