Chapter 4 Multithreading in Java PDF
Chapter 4 Multithreading in Java PDF
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Multiprocessing in java is a executing multiple process simultaneously
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process. Java Multithreading is mostly used in games, animation etc.
Multithreading enables to write very efficient program that make maximum use of CPU.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU.
Multitasking can be achieved by two ways:
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
Page 1
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
o Thread is lightweight.
o Threads share the same address space.
o Cost of communication between the thread is low.
Page 2
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
In a Java program a main thread is actually a main thread module which is the creating and starting
point for all other threads A, B and C. Once initiated by main thread they can run concurrently and share the
resources jointly.
Threads running in parallel do not actually mean that they are running at the same time. Since, all
threads are running on the single processor, the flow of execution is shared among the threads. The Java
interpreter handles the context switching of control among threads insuch a way that they runs concurrently.
1)Single-threaded systems use an approach called an event loop with polling. In this system, a single
thread of control runs in an infinite loop, polling a single event queue to decide what to do next. Once this
polling mechanism returns with, a signal that a network file is ready to be read, then the event loop
dispatches control to the appropriate event handler. Until this event handler returns, nothing else can happen
in the system. This wastes CPU time. It can also result in one part of a program dominating the system and
preventing any other events from being processed. In general, in a singled-threaded environment, when a
thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops
running.
2)Multithreded System- Java’s multithreading is that the main loop/polling mechanism is eliminated. One
thread can pause without stopping other parts of your program. For example, the idle time created when a
thread reads data from a network or waits for user input can be utilized elsewhere. Multithreading allows
animation loops to sleep for a second between each frame without causing the whole system to pause. When
a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to
run.
Page 3
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Newborn state
After creation of the thread object, the thread is born which is called as newborn thread. This
thread is not scheduled for running. We can either start this state to make it runnable using start( )
method or kill the thread using stop( ) method. Only these two operations can be performed on
this state of the thread. If we attempt to perform any other operation, the exception will be
thrown.
Runnable state
When the thread is ready for execution and is waiting for availability of the processor, it is said to
be in runnable state. The thread has joined the queue of threads that are waiting for execution
If all the threads have equal priority, then they are given time slots for execution in round robin
fashion i.e. on first come first serve basis. The thread that relinquishes control joins the queue at the end
and again waits for its execution. This process of assigning time to threads is known as time slicing. If
we want a thread to relinquish control to another thread of equal priority, a yield ( ) method can be used.
Running state
When the processor has given time to the thread for its execution then the thread is said to be in
running state. The thread runs until it relinquishes control to its own or it is pre-empted by a higher
priority thread. A running thread may relinquish its control in any one of the following situations:
1. The thread has been suspended using suspend( ) method. This can be revived by using resume( )
method. This is useful when we want to suspend a thread for some time rather than killing it.
2. We can put a thread to sleep using sleep (time) method where ‘time’ is the time value given in
milliseconds. Means, the thread is out of queue during this time period.
3. A thread can wait until some event occurs using wait( ) method. This thread can be scheduled to run
again using notify( ) method.
Blocked state
When a thread is prevented from entering into the runnable state and subsequently in running
state it is said to be blocked. 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.
Dead state
A running thread ends its life when it has completed its execution of run( ) method. It is a natural
death. However we can kill it by sending the stop message to it at any state thus causing a premature
death to it. A thread can be killed as soon as it is born or while it is running or even when it is in blocked
state.
All the Java programs are at least single threaded programs. When a Java program starts up, one
thread begins running immediately. This is usually called the main thread of the program, because it is the
one that is executed when our program begins. The main thread is important for two reasons:
a. It is the thread from which other “child” threads can be initiated
b. Generally it must be the last thread to finish execution because it performs various shutdown
actions.
Though the main thread is created automatically when the program is started, it can be controlled
through a Thread object. For this, we must obtain a reference to it by calling the method currentThread( ),
which is a public static member of Thread class. Its general form is as shown below:
Page 4
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
This method returns a reference to the thread in which it is called. Once we obtained a reference to
the main thread, we can control it just like any other thread.
Observe the output of program when ‘t’ is used as an argument to println( ). This display, in order: the name
of the thread, its priority, and the name of the thread group to which it belongs. By default, the name of the
main thread is main. Its priority is 5, which is also the default value, and main is also the name of the group
of threads to which this thread belongs. A thread group is a data structure that controls the state of a
collection of threads as a whole. This process is managed by the particular run-time environment. After the
name of the thread is changed, t is again displayed. This time, the new name of the thread i.e. “Prime
Thread” is displayed.
The sleep( ) method causes the thread from which it is called to suspend execution for the specified
period of milliseconds. Its general form is:
The number of milliseconds to suspend is specified in milliseconds. This method may throw an
InterruptedException. The sleep( ) method has another form, which allows us to specify the period in terms
of milliseconds as well as nanoseconds:
Page 5
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
we can set the name of a thread by using setName( ). We can obtain the name of a thread by calling
getName( ). These methods are members of the Thread class and are declared as:
Thread class: Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Page 6
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you
have to follow these steps:
7
8
9
10
No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be
thrown.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Throw the Exception
}
When a thread is in running state, and you try to start it again, or any method try to invoke
that thread again using start() method, exception is thrown.
Creating a thread using Runnable interface - step by step approach
Output :
C:\Program Files\Java\jdk1.7.0_71\bin>javac MyThreadDemo1.java
C:\Program Files\Java\jdk1.7.0_71\bin>java MyThreadDemo1
Thread Running
If you are not extending the Thread class,your class object would not be treated as a thread
Page 8
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
This method returns true if the thread upon which it is called is still running else returns
false. The join( ) method is used to wait for the thread to finish. Its general form is:
This method waits until the thread on which it is called terminates. Its name comes from the concept
of the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow us
to specify a maximum amount of time that we want to wait for the specified thread to terminate.
Thread Priority
Each thread have a priority, Thread priorities are used by the thread scheduler to decide when each
thread should be allowed to run. Or at what time the thread is to be executed. when thread assigned a priority
which affect the order in which threads are scheduled for execution or running. Thread priority is used to
decide when to switch from one running thread to another.
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Higher-priority threads get more CPU time than lower-priority threads. the amount of CPU time
that a thread gets often depends on several factors besides its priority. (For example, how an operating
system implements multitasking can affect the relative availability of CPU time.) A higher-priority thread
can also pre-empt a lower-priority one. For instance, when a lower-priority thread is running and a higher-
priority thread resumes (from sleeping or waiting on I/O, for example), it will pre-empt the lower-priority
thread
Priorities are represented by a number between 1 and 10. In most cases, thread scheduler schedules
the threads according to their priority. There are 3 constant values as
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.
To set a thread's priority, use the setPriority ( ) method, which is a member of Thread. This is
its general form:
Page 9
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Here, level specifies the new priority setting for the calling thread. The value of level must be within
the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities
are defined as final variables within Thread.
We can obtain the current priority setting by calling the getPriority( ) method of Thread, shown
here:
final int getPriority( )
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Test it Now
Page
10
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Thread synchronization
Java support multithreading, in multithreaded application thread might want to access the
data and call methods simultaneously and this may create problem such as violation of data and
unpredictable result. These problems are referred as concurrency problem. Synchronization is the
technique that can be used to overcome the concurrency problem that may occur when when
multiple threads try to access the same resource.
What is Synchronization?
“When more than one thread uses same resource one should ensure that the resource
may be used by only one thread at a time this process is called Synchronization”.
Java uses the concept of semaphore for synchronization. This is similar to lock whenever a thread is
making an attempt to use shared resources it will lock the resource and then after using it , it will
release the resource.
Key to synchronization is the concept of Monitor
Monitor is an object that is used as a mutually exclusive lock.
When thread acquires a lock, it is said to have entered in the monitor and thread has
to wait.
Syntax to use synchronized block
class Message
Page
12
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
{
void display( )
{
System.out.println("HI");
System.out.println("I");
System.out.println("AM");
System.out.println("LEARNING");
System.out.println("JAVA");
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
Page
13
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Output
C:\Program Files\Java\jdk1.7.0_71\bin>javac syncdemo.java
See the output of above example the output is not proper it means one thread which ob1
take the control of CPU & before it complete all operation in the display method the thread is forced
to sleep by method sleep() the second thread which is created object ob2 take the control and start
printing the message so output will be mixed and unexpected as shown.
So to solve the above problem & to get correct output you must restrict the access
to the method display() to only one thread at a time. To do this you simply need to precede display()
with the keyword ‘synchronized ’ like this
synchronized void display( )
{ ......................
......................
}
After changes in the program output will be:
C:\Program Files\Java\jdk1.7.0_71\bin>javac syncdemo.java
C:\Program Files\Java\jdk1.7.0_71\bin>java syncdemo
HI
I
AM
LEARNING
JAVA
HI
I
AM
LEARNING
JAVA
Page
14
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Q1. Write a program to create two threads; one to print numbers in original order and
other to reverse order from 1 to 50.( 4-marks for Logic, 4-marks for correct Syntax)
Or
{
public void run()
{
for (int i=1; i<=50; i++)
{
System.out.println("Message from First Thread : " +i);
}
}
}
class SecondThread extends Thread
{
public void run()
{
for (int i=50; i>0; i--)
{
System.out.println( "Message from Second Thread : " +i);
}
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FirstThread firstThread = new FirstThread();
SecondThread secondThread = new SecondThread();
firstThread.start();
secondThread.start();
}
}
Q2. Write a program to create two threads; one to print prime numbers and other to non prime
number from 1 to 20.( 4-marks for Logic, 4-marks for correct Syntax)
}
}
class nonprime extends Thread
{
public void run()
{
int i=0,j=0;
for(i=2;i<11;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
break;
}
if(i!=j)
System.out.println(i+" is not a prime no.");
try{
sleep(500);
}
catch(Exception e){}
}
}
}
class primeThread
{
public static void main(String args[])
{
prime p=new prime();
nonprime n=new nonprime();
System.out.println("Start main");
System.out.println("1 is universal constant");
p.start();
n.start();
}
}
Q3. Write a program to create two threads; one to print Odd numbers and other to Even number
from 1 to 20.( 4-marks for Logic, 4-marks for correct Syntax)
}
}
class odd extends Thread
{
public void run()
{
for(int i=1; i<=20;i++)
{
if(i%2!=0)
System.out.println("\t odd number="+i);
}
}
}
class oddeven
{
public static void main(String args[])
{
even a=new even();
odd b=new odd();
a.start();
b.start();
}
}
Q4. Write a program to create two threads; one to print given array in ascending order and other
to print descending order .( 4-marks for Logic, 4-marks for correct Syntax)
}
}
Page
20
Chapter 4 Multithreading in Java Prof. Mr. Nanaware Dattatray Bapurao
Thread Exceptions
ThreadDeath :
An instance of ThreadDeath is thrown when the Thread.stop() method is invoked.
Page
21