JAVA - 7 - Multithreading Programming - Doc
JAVA - 7 - Multithreading Programming - Doc
JAVA - 7 - Multithreading Programming - Doc
Multithreading programming
• Introduction to multithreading
• The Java thread model (Life cycle of thread)
• The main thread
• Creating a thread
• Creating multiple threads.
• Using alive( ) & join( )
• Thread priorities
• Synchronization
• Inter thread communication
• Suspending, resuming, stopping threads
Introduction
• Program is a sequence of statements.
• A Program may be divided into two or more sub programs, this sub programs are
called process.
• Many Processes can be implemented at the same time in parallel (parallel Execution).
• Process can be divided into further small parts in its sub process (threads).
• That sub-process is called Thread.
• We can say “Thread” is a smallest unit of a program.
Important terms
• Multiprogramming: More than one program running at same time. That can share
same Processor.
• Multiprocessing: two or more processes of a program running at same time. They can
process on the own (different) memory location.
• Multithreading: two or more thread of a process executing in parallel. That can share
same memory location in the memory.
• Multitasking: multiple task performed at a time
Difference between Thread based and process base Multitasking
Single program can perform two or more Process based multitasking allows your
3 task simultaneously. computer to run two or more program.
Each thread of same process shared the Each process has independent execution
same state, same memory space and can units that contain their own state
communicate with each other directly. information, address spaces, and interact
4
Because they share same variable. So with each other via IPC.
threads are known as Light weight
process.
E.g. Text editor can format text a t the You can run java compiler at the same time
same time that it is printing that that you are using a text editor
5 document. These two actions are being
performed by two separate threads
Multithreading Concept
• Multithreading is a conceptual programming paradigm where a program ( or
process) is divided into two or more subprograms( or process),which can be
implemented at the same time in parallel.
• Java enables us to use and manage multiple flows of control in developing
programs.
• Each flow of control may be thought of as a separate tiny program, which is known
as thread that runs in parallel to others threads of the same process.
• Threads in java are subprograms of main application program and share the same
memory space, they are known as light weight process.
• Once any thread of the process initiated then the remaining threads run concurrently
and share the same resources jointly.
• Multithreading is similar to dividing a task into subtasks and assigning them to
different people for execution independently and simultaneously, to achieve a single
desire.
• E.g. In animation, one sub program can display an animation on the screen while
another may build the next animation to be displayed.
• Threads are extensively used in java enabled browsers such HotJava. These
browsers can download a file to the local computer, display a web page in the
window, and output another web page to a printer and so on.
• If we are working on any application that requires two more things to be done at the
same time, then threads are best to use.
Here, Java program with four threads, one main and three others. Here main thread is
designed to create and start the other three threads namely A, B and C.
Note:
• Actually, we have only one processor and therefore in reality the processor is doing
only one thing at time. However, the processor switches between the processes so fast
that it appears to all of them are being done simultaneously.
• Threads’ running in parallel does not really mean that they actually run at the same
time. Actually, all threads are running on a single processor, the flow of execution is
shared between threads.
• Java interpreter handles the switching of control between the threads in such a way that
it appears they are running concurrently.
Use:
We can divided a long program into threads and execute them in parallel, so we can
use each and every resources efficiently.
We can send tasks into background and continue to perform some other task in the
foreground. This increase speed of our program.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states. It can move from one state to another via
a variety of ways.
2) Runnable state
• Runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
• The threads has joined waiting queue for execution.
• If all threads have equal priority, then they are given time slots for execution in round
robin fashion. i. e. first-come, first serve manner.
• Thread which is relinquishes (leaves) control, joins the queue at the end and again
waits for its turn. This process of assigning time to thread is known as time-slicing.
• If we want a thread to relinquish(leave) control to another thread of equal priority
before its turn comes ,then yield( ) method is used
3) Running state
• Running means that processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher
priority thread.
• A running thread may change its state to another state in one of the following
situations.
1) When It has been suspended using suspend ( ) method.
A suspended thread can be reviewed by resume ( ) method.
This is used when we want to suspend a thread for some time due to certain reason, but
do not want to kill it.
4) Blocked state
• A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state.
• 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.
5) Dead state
• Every thread has a life cycle. A running thread ends its life when it has completed
executing its run ( ) method.
• It is natural death. However we can kill it by sending the stop message to it as any state
thus causing a premature death for it.
• A thread can be killed as soon it is born or while it is running or even when it is in
“blocked” condition.
Main thread
• When a java program starts up, one thread begins running immediately.
• It is the one that is executed when your program begins, so it is usually called the main
thread of your program.
• Main thread is important for two reason:
It is the thread from which other “child” threads will be created.
It must be the last thread to finish execution because it performs various
shutdown actions.
• Main thread is created automatically when your program is started .it can be controlled
through a Thread object.
• We can refer that object by calling the method currentThread() which is public static
member of Thread.
Syntax: static Thread currentThread ( )
• This method returns reference to the thread in which it is called. If we have reference
to main thread, we can control it as any other thread.
• By default, the name main thread is main.
• Thread group is a data structure that controls the state of a collection of threads as a
whole. It is managed by the particular run-time environment.
Example: controlling the main Thread
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t =Thread. currentThread ( );
System.out.println (“Current thread:”+ t);
t. setName (“Mythread”);
System.out.println (“After name change:” + t);
t. setPriority(10);
System.out.println (“After Priority set:” + t);
try
{
for(int n=5; n>0 ;n--)
{
System.out.println (n);
Thread. sleep (1000);
}
}
catch (InterruptedException e)
{
System.out.println (“Main thread interrupted “);
}
}
}
Output: Current thread: Thread [main, 5, main]
After name change: Thread [My Thread, 5, main]
After Priority set: Thread [My Thread, 10, main]
5
4
3
2
1
The Thread class declares the run ( ) method that is required for overriding threads in
our programs.
We can make our class runnable by extending the class java.lang.Thread.
To extend Thread class, perform following steps:
1. Declare the class as extending the Thread class.
2. Implement the run ( ) method that is responsible for executing the sequence of code
that the thread will execute.
3. Create a thread object and call the start ( ) method to initiate the thread execution .
Step 1: Declaring the class
Thread class can be extended as follows:
class MyThread extends Thread
{
………..
………..
} now we have new type of thread MyThread.
Step 2: Implementing the run ( ) interface
The run ( ) method has been inherited by the class MyThread. We have
overridden this method to implement the code executed by our thread.
public void run( )
{
……….. //Thread code here
}
When we start the new thread, java calls the thread’s run ( ) method, so it
is the run ( ) where all the actions takes place.
Step3: starting new thread
To actually create and run an instance of our thread class, we must write:
MyThread aThread =new MyThread ( );
aThread .start( ); // invokes run() method
Or
new MyThread( ).start ( );
Then java runtime will schedule the thread to run by invoking its run ( ) method,
Now thread is said to be in the running state.
}
class B extends Thread
{
public void run( )
{
for (int j=1; j<=5;j++)
{
System.out.println (“\t from Thread B: j =”+j);
}
System.out.println (“Exit from B”);
}
class C extends Thread
{
public void run()
{
for (int k=1; k<=5;k++)
{
System.out.println (“\t from Thread C: k =”+k);
}
System.out.println (“Exit from C”);
}
class ThreadTest
{
public static void main(String args[])
{
new A( ).start(); //step3
new B( ).start();
new C( ).start();
}
}
Output:
First run
From Thread A : i = 1
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit form A
From Thread B : j = 5
Exit from B
From Thread C :k = 5
Exit from C
Exit from B
In Multi-threading, one thread can know when another thread has ended or not by
using two methods isAlive ( ) and join ( ) method.
1) isAlive() :
• We can know state of any thread by these methods.
• This method is defined by Thread class .its general form is :
final boolean isAlive ( )
It returns true if the thread upon which it is called is still running, It returns false
otherwise.This method is occasionally useful.
2) Join() :
• The join method causes the current thread to wait until the thread upon which the join ( )
method is call, gets terminates.
• It s name comes from the concept of calling thread waiting until the specified thread
joins it.
• join ( ) also allows to specify a maximum amount of time that user want to wait for the
specified thread to terminate.
• This method is defined by Thread class .its general form is :
final void join( ) throws InterruptedException
Where the join () method either suspends the current thread for timeout
milliseconds or until the thread it calls on terminates.
• This method is commonly used.
Example of isAlive ( ) and join ( )
t1.start ( );
t2.start ( );
t3.start ( );
try
{
System.out.println (“Thread t1 is alive:” + t1.isAlive ( ));
System.out.println (“Waiting for finishing threads t1”);
class ThreadPriority
{
public static void main(String args[])
{
A t1=new A ( );
B t2=new B ( );
C t3=new C ( );
Output:
Start thread A
Start thread B
Start thread C
threadB started
from thread B: j=1
from thread B: j=2
threadC started
from thread C: j=1
from thread C: j=2
from thread C: j=3
from thread C: j=4
Exit from C
End of main thread
from thread B: j=3
from thread B: j=4
Exit from B
threadA started
from thread A:i=1
from thread A: i=2
from thread A: i=3
from thread A: i=4
Exit from A
Thread Exception
• The call to sleep ( ) method should enclosed in a try block and followed by a catch
block. This is necessary because the sleep ( ) method throws an exception, which
should be caught.
• Java run system will throw IllegalThreadStateException whenever we attempt to
invoke a method that a thread cannot handle in the given state.
Ex: sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions.
• Whenever we call a thread that may throw an exception, we have to supply appropriate
exception handler to catch it.
• Here ,the example of different Exception in multithreading are given in next slide:
catch (ThreadDeath e)
{
………………
……………… //Killed threads
}
catch( InterruptedException e)
{
……………… //cannot handles it in the current state
………………
}
catch (IllegalArgumentException e)
{
……………… //illegal method argument
………………
}
catch (Exception e)
{
………………
………………
}
Synchronization
• When two or more threads need to 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 of
achieving this is called synchronization.
For example, one thread may try to read a record from a file while another is
still writing to the same file. Depending on situation we may get strange result. We can
avoid this by synchronization.
• Monitor (semaphore) concept is key to synchronization.
• Monitor is an object that is used as a mutually exclusive lock or mutex.
• Only one thread can own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the monitor. Monitor is like a
key and the thread that holds the key can only open the lock.
• All the other threads attempting to enter the locked monitor will be suspended until the
first thread exists the monitor. This other threads are said to be waiting for the monitor.
Dead lock
• When two or more threads are waiting to gain control of a resources which are already
hold by another waiting threads, and no one can further proceed, such situation is
known as deadlock.
Ex:
Thread A: synchronized method2()
{
synchronized method1()
{
……………..
}
}
Thread B: synchronized method1()
{
synchronized method2()
{
……………..
}
}
Interthread communication
• Polling is used to check some condition repeatedly. Once the condition is true
appropriate action is taken.
• In polling system, consumer would waste many CPU cycles, while it waited for the
producer to produce. Once producer complete it waits for to complete consumer to
finish.
• To avoid polling, Java includes inter process communication mechanism via the wait
(), notify( ) and notifyAll ( ) methods.
• These methods are implemented as final methods in object. (in package
java.lang.Object)
• All three methods can be called only from within a synchronized context.
1. Wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify().
Syntax: final void wait () throws InterruptedException
2. notify() wakes up the first thread that called wait () on the same object.
Syntax: final void notify()
3. notifyAll() wakes up all the threads that called wait() on the same object. The highest
priority thread will run fast.
Syntax : final void notifyAll()
Suspending, resuming & stopping threads
1. Stopping a thread :stop()
syntax : threadName.stop();
This causes the thread to move to dead state.A thread will also move to the dead
state automatically when it reaches the end of its method.
• The stop( ) method may be used when the premature death of a read is desired.
2. Resuming thread
syntax : threadName.resume();
• This causes the thread to move to runnable state.A thread will also move to the dead
state automatically in certain situation.
3. Suspending thread :sleep() ,wait() and suspend()
This all causes the thread to move to Blocked state
• threadName.sleep(t); This makes thread to sleep for t time (in milisecond),
after time elapsed thread will goes into runnable state.
• threadName.wait(); This tells thread to wait for some event to complete, to
gain control notify() method is called of that thread.
• threadName.suspend(); This suspends thread for some reason and then using
resume () method thread goes into runnable state.
---------------------------------------*--------------------------------------