20ES3102 – Java Programming
UNIT-III
Chapter 3: Multithread Programming
Multithreading
Multithreading is a conceptual programming concept where a program (process) is divided into
two or more subprograms (process), which can be implemented at the same time in
parallel.Amultithreadedprogramcontainstwoormorepartsthatcanrunconcurrently.Each
partofsuchaprogramiscalledathread,andeachthreaddefinesaseparatepathofexecution. A
process consists of the memory space allocated by the operating system that can contain one
or more threads. A thread cannot exist on its own; it must be a part of aprocess.
There are two distinct types of Multitasking i.e. Processor-Based and Thread-Based
multitasking.
Q: What is the difference between thread-based and process-based multitasking?
Ans: As both are types of multitasking there is very basic difference between the two. Process-
Based multitasking is a feature that allows your computer to run two or more programs
concurrently. For example you can listen to music and at the same time chat with
yourfriendsonFacebookusingbrowser.InThread-basedmultitasking,threadisthesmallest unit of
code, which means a single program can perform two or more tasks simultaneously. For
example a text editor can print and at the same time you can edit text provided that those two
tasks are perform by separatethreads.
Q: Why multitasking thread requires less overhead than multitasking processor?
Ans:Amultitaskingthreadrequireslessoverheadthanmultitaskingprocessorbecauseofthe
followingreasons:
Processes are heavyweight tasks where threads arelightweight
Processes require their own separate address space where threads share the address
1
space
Interprocess communication is expensive and limited where Interthread
communication is inexpensive, and context switching from one thread to the next is
lower incost.
Benefits of Multithreading
1. Enables programmers to do multiple things at onetime.
2. Programmers can divide a long program into threads and execute them in parallel
which eventually increases the speed of the programexecution
3. Improved performance andconcurrency
4. Simultaneous access to multipleapplications
5. You can perform many operations together so it saves time.
6. Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
Life Cycle of Thread
A thread can be in any of the five following states
1. Newborn State: When a thread object is created a new thread is born and said to be in
Newbornstate.
2. Runnable State: If a thread is in this state it means that the thread is ready for
executionandwaitingfortheavailabilityoftheprocessor.Ifallthreadsinqueueareof
sameprioritythentheyaregiventimeslotsforexecutioninroundrobinfashion
3. Running State: It means that the processor has given its time to the thread for execution. A
thread keeps running until the following conditionsoccurs
a. Thread give up its control on its own and it can happen in the following situations
i. A thread gets suspended using suspend() method which can only be revived
with resume()method
ii. A thread is made to sleep for a specified period of time using sleep(time)
method, where time inmilliseconds
2
iii. Athreadismadetowaitforsomeeventtooccurusingwait()method. In this case a
thread can be scheduled to run again using notify () method.
b. A thread is pre-empted by a higher prioritythread
4. Blocked State: If a thread is prevented from entering into runnable state and subsequently
running state, then a thread is said to be in Blockedstate.
5. DeadState:ArunnablethreadenterstheDeadorterminatedstatewhenitcompletes its task or
otherwiseterminates.
Fig: Life Cycle of
Thread
Main Thread
Every time a Java program starts up, one thread begins running which is called as the main
thread of the program because it is the one that is executed when your program begins.
Child threads are produced from mainthread
Often it is the last thread to finish execution as it performs various shut down operations
3
Creating a Thread
Java defines two ways in which this can be accomplished:
You can implement the Runnableinterface.
You can extend the Thread class,itself.
Create Thread by Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
ToimplementRunnable,aclassneedonlyimplementasinglemethodcalledrun(),whichis
declared likethis:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important
tounderstandthatrun()cancallothermethods,useotherclasses,anddeclarevariables,just like
the main threadcan.
After you create a class that implements Runnable, you will instantiate an object of type
Threadfromwithinthatclass.Threaddefinesseveralconstructors.Theonethatwewilluseis
shownhere:
Thread(Runnable threadOb, String threadName);
HerethreadObisaninstanceofaclassthatimplementstheRunnableinterfaceandthename of the
new thread is specified by threadName. After the new thread is created, it will not start
running until you call its start( )method, which is declared within Thread. The start( )
method is shownhere:
void start( );
4
Example to Create a Thread using Runnable Interface
Output:
Create Thread by Extending Thread
The second way to create a thread is to create a new class that extends Thread, and then to create an
instance of that class. The extending class must override the run( ) method,
Which is the entry point for the new thread. It must also call start( ) to begin execution of the
new thread.
Example to Create a Thread by Extending Thread Class
5
Output:
Thread Methods
SN Methods with Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this
Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread
to block until the second thread terminates or the specified number of milliseconds
passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final booleanisAlive()
Returns true if the thread is alive, which is any time after the thread has been started
but before it runs to completion.
Q: Can we start a thread twice?
Ans: No, if a thread is started it can never be started again, if you do so, an
illegalThreadStateException is thrown. Example is shown below in which a same thread is
coded to start again
6
Asyoucanseetwostatementstostart
a same thread is written in the code
which will not give error during
compilation but when you run it you can
see an Exception as shown in the Output
Screenshot.
Output:
Use of Yield() Method
Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled
Creating Multiple Threads and use of yield method:
7
Example
Condition is checked and when i==2
yield() method is evoked taking control
to thread B
As you can see in the output below, thread A gets started and when condition if(i==2) gets
satisfied yield() method gets evoked and the control is relinquished from thread
AtothreadBwhichruntoitscompletionandonlyafterthatthreadaregainthecontrol back.
8
Output
Use of stop() Method
The stop() method kills the thread on execution
Example
Condition is checked and when i==2
stop() method is evoked causing
termination of thread execution
Output
Use of sleep() Method
Causes the currently running thread to block for at least the specified number of milliseconds.
You need to handle exception while using sleep() method.
9
Example
Condition is checked and when i==2 sleep()
method is evoked which halts the
execution of the thread for 1000
milliseconds. When you see output there is
no change but there is delay in execution.
Output
Use of suspend() and resume() method :A suspended thread can be revived by using the resume()
method. This approach is useful when we want to suspend a thread for some time due to certain reason
but do not want to kill it.
Following is the example in which two threads C and A are created. Thread C is started ahead
of Thread A, but C is suspended using suspend() method causing Thread A to get hold of the
processor allowing it to run and when Thread C is resumed using resume() method it runs to
its completion.
Example
10
Although Thread ‘C’ is started earlier
than Thread ‘A’ but due to suspend
method Thread ‘A’ gets completed ahead
of Thread ‘C’
Output
Thread Priority
EveryJavathreadhasaprioritythathelpstheoperatingsystemdeterminetheorderinwhich threads
11
arescheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processortimebeforelower-prioritythreads.However,threadprioritiescannotguaranteethe order
in which threads execute and very much platformdependent.
Example
In the above code, you can see Priorities of Thread is set to maximum for Thread A which lets
it to run to completion ahead of C which is set to minimum priority.
Output:
Use of isAlive() and join() method
Thejava.lang.Thread.isAlive()methodtestsifthisthreadisalive.Athreadisaliveifithasbeen
startedandhasnotyetdied.Followingisthedeclarationforjava.lang.Thread.isAlive()method
12
public final booleanisAlive()
This method returns true if this thread is alive, false otherwise.
join() method waits for a thread to die. It causes the currently thread to stop executing until
the thread it joins with completes its task.
Example
At this point Thread A is
alive so the value gets
printed by isAlive() method
is “true”
join() method is called from
Thread A which stops
executing of further
statement until A is Dead
Now isAlive() method
returns the value false as
Output the Thread A is complete
Synchronization and use of synchronized keyword
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this synchronization
is achieved is called thread synchronization. The synchronized keyword in Java creates a block
of code referred to as a critical section. Every Java object with a critical
sectionofcodegetsalockassociatedwiththeobject.Toenteracriticalsection,athreadneeds to obtain
13
the corresponding object'slock.
synchronized(object)
// statements to be synchronized
Problem without using Synchronization
In the following example method updatesum() is not synchronized and access by both the
threads simultaneously which results in inconsistent output. Making a method synchronized,
Java creates a “monitor” and hands it over to the thread that calls the method first time. As long
as the thread holds the monitor, no other thread can enter the synchronized section of the code.
Writing the method as synchronized will make one thread enter the method and till execution
is not complete no other thread can get access to the method.
14
Output when
method is declared
as synchronized
Output
Interthread Communication
It is all about making synchronized threads communicate with each other. It is a
15
mechanism in which a thread is paused running in its critical section and another thread
is allowed to enter in the same critical section to be executed. It is implemented by the
following methods of Object Class:
wait( ): This method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify().
notify():Thismethodwakesupthefirstthreadthatcalledwait()onthesameobject.
notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.
The highest priority thread will runfirst.
ThesemethodsareimplementedasfinalmethodsinObject,soallclasseshavethem.Allthree
methods can be called only from within a synchronizedcontext.
Example
If both these methods are commented which
means there is no communication, output will be
inconsistent. See Output 2
16
Output 1:
Output 2:
17