Professional Documents
Culture Documents
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:
Learning Outcomes
At the end of this chapter, you are expected to:
• 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
• Describe the methods of the thread class used to schedule the threads
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.
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
• Increase the speed of program execution by dividing the program into threads and
execute them in parallel.
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.
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.
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.
189
e1.start();
while(true)
{ // (4)
Thread.State state = e1.getState();
System.out.println(state);
if (state == Thread.State.TERMINATED) break;
}
}
}
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).
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.
Multithreaded features are utilised using Constructors of Thread classes. Some of them are:
1. Thread ( )
3. Thread (Runnable r)
191
Thread class defines methods for managing threads. Some of the methods are as follows:
Method Description
Method Description
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:
192
• It allows, or its run method exits.
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.
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”:
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( )
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
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
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.
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");
}
}
}
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()
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.
197
For example,
An example of Runnable interface that creates a new thread and starts it running, which is given
below:
198
Within NewThread’s constructor, a new Thread object is created by the following statement:
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.
Note: Your output may vary based on processor speed and task load.
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Main Thread: 2
Main Thread: 1
199
For example,
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)
For an example, the following program creates three child threads for this code:
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.");
}
}
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.
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)
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.
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.
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.
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:
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
}
• 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
209
Syntax - public void suspend( )
Resuming a Thread is a process of making a thread resume to its original running state after
suspending.
Stopping a Thread is a process of stopping a thread completely. It can be done using stop( )
method.
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
Thread: Thread-2, 6
Thread: Thread-2, 5
Thread: Thread-2, 4
Thread: Thread-1, 6
212
Thread: Thread-1, 5
Thread: Thread-1, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
The thread class also describes a method called stop( ) that ends a thread. Its signature is shown
here:
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.
Terminal Questions
1. Describe the life cycle of a thread.
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:
216
Bibliography
External Resources
• (2016). Retrieved 12 June 2016, from http://www.freejavaguide.com/java-threads-
tutorial.pdf
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