Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 74

Multithreading

Multithreading
• Multithreading in java is a process of executing
multiple threads simultaneously.
• A Multi threaded program contains two or more parts
that can run concurrently.
• Each part of a program is called a thread.
• Multi threading is a specialized form of multi tasking.
Multitasking Fundamentals
• Multitasking is a process of executing multiple tasks
simultaneously.
• We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Multi Threading Fundamentals
Process based multi tasking:
•A feature that allows to execute two or more programs concurrently.
•Here a program is the smallest unit of code that can be dispatched
by the scheduler.
Eg: running the java compiler, using text editor or browsing the
internet simultaneously…
Thread based Multitasking:
•Here the thread is Smallest unit of dispatchable code.
• single program can perform two or more tasks at once.
Eg: a text editor can be formatting text at the same time that
it is printing, as long as these two actions are being performed by
two separate threads.
Process-based vs. Thread-based
1. A process is a program that is 1. A thread is a separate path of
executing. execution.

2. Processes are heavy weight tasks 2. Threads are light weight process.
that require their own separate They share the same address space
address spaces.
3. Interprocess communication is 3. Inter thread communication is
expensive and limited. inexpensive.

4. Context switching from one 4. Context switching from one thread


process to another is also costly. to the next is low cost.
What is Thread in java

• A thread is a lightweight sub


process, a smallest unit of
processing.
• It is a separate path of
execution.
• Threads are independent, if
there occurs exception in one
thread, it doesn't affect other
threads.
• It shares a common
memory area.
Advantages of Java Multithreading
• It doesn't block the user because threads are
independent and you can perform multiple operations
at same time.
• You can perform many operations together so it
saves time.
• Threads are independent. so it doesn't affect other
threads if exception occur in a single thread.
Thread Life Cycle
Thread can exist in several states:
The life cycle of the thread in java is controlled by JVM.
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
Thread Life Cycle
Thread can exist in several states:
New State:
• After the creations of Thread instance the thread is in this state but before
the start() method invocation. At this point, the thread is considered not alive.
Ready (Runnable) State:
• A thread start its life from Runnable state.
• A thread first enters runnable state after the invoking of start() method but a
thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also.
• On this state a thread is waiting for a turn on the processor.
Thread Life Cycle (Contd..)
Running State:
• A thread is in running state that means the thread is currently
executing.
• There are several ways to enter in Runnable state but there is
only one way to enter in Running state: the scheduler select a
thread from runnable pool.
Blocked State:
• A thread can enter in this state because of waiting the resources
that are hold by another thread.
Dead State:
• A thread can be considered dead when its run() method completes.
• If any thread comes on this state that means it cannot ever run
again.
Thread Life Cycle
Thread Life Cycle (Contd..)
• Starting from the birth of a thread, till its death, a thread exists in
different states which are collectively called “Thread Life
Cycle”.
• A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
• A thread goes into runnable state when start() method is applied
on it.
• That is void start() method is used to call the public void run()
method.
• From runnable state, a thread may get into non-runnable state,
when sleep() or wait() or suspend() methods act on it.
• notify() and resume() methods are used to restart waiting and
suspended threads respectively.
Thread Life Cycle (Contd..)

• yield() method causes the currently executing thread object to


temporarily pause and allow other threads to execute.
• ThreadDeath class will be invoked whenever the stop() method
is called.
The Thread class and Runnable interface
• Java’s multithreading is built on the Thread class and its
companion interface, Runnable.
• Both are packaged in java.lang package.
• In every java program, there is always a thread running internally.
This thread is used by JVM to execute the program statements.
• When a Java program starts up, one thread begins running
immediately.
• This is usually called the main thread of your program, because it
is the one that is executed when your program begins.
main Thread
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be
spawned.
• Often it must be the last thread to finish execution because it
performs various shutdown actions.
Creating A Thread

• Java defines two ways of creating a Thread.


1. By Implementing Runnable interface.
2. By Extending The Thread class.
Creating A Thread :By Implementing
Runnable interface.
• We have an interface called Runnable with only one method
public void run().
interface Runnable
{
public void run();
}
• The class which implements Runnable interface has to implement the method
run().
• Inside run() we can define the code.
• run() can also call other methods.
• After instantiating the class we will pass it to Thread class
–Thread(Runnable obj);
Creating A Thread :By Implementing
Runnable interface.
General form:
class classname implements Runnable
{
public void run()
{
// write code
}
}
class Tdemo
{ public static void main(String args[])
{
//create object of the above class say obj
Thread t1= new Thread(obj);
t1.start();
}}
Creating A Thread :By
Implementing Runnable interface.
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  

Runnable Interfaces
Output
Creating A Thread :By Extending Thread
class
General form:
class classname extends Thread{
public void run(){ //write code here}
}
class Tdemo{
public static void main(String args[]){
//create the object for above class say t1
//call start() method of Thread class
t1.start();
}
}
Creating A Thread :By Extending
Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
Output:
• thread is running….
Output
Extending Thread vs Implementing
Runnable interface
Extending Thread Implementing Runnable interface
class A extends Thread Class A implements runnable
{ public void run() { } } {public void run() { }
class Ademo{ }
A a1=new A(); Class Ademo{
a1.start(); A a1=new A();
} Thread t=new Thread(a1);
t1.start();}

We can override the other methods of We can only implement only run
thread also along with run(). method.
We can not inherit other classes. We can inherit other classes also.
Methods in Thread class
• currentThread() method returns a reference
to the currently executing thread object.
• getName() method returns this thread's name.
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or
not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified
time
start() start a thread by calling run()
method
Constructors of Thread class

• Thread ( )
• Thread ( String str )
• Thread ( Runnable r )
Thread Class Constructors
1. Thread() Allocates a new Thread Object.
E.g., Thread t=new Thread();

2. Thread(String name) Allocates a new thread.


E.g., Thread t= new Thread( “FirstChild”);

3. Thread(Runnable target) Allocates a new Thread object.


E.g., SecondThread st= new SecondThread();
Thread t=new Thread(st);
Thread ( ) and Thread ( String str )

• First constructor is used to create object of thread class. 


Second constructor is also used to create object of thread class with
required name. 
Eg: 
1)Thread t1=new Thread(); 
This creates a thread class object t1. 
2)Thread t2=new Thread(“MYTHREAD”); 
This also creates Thread class object t2 .
It also creates thread with name "MYTHREAD". 
Thread Class Constructors
• Thread ( Runnable r )
• Thread ( Runnable r, String str)

3. Thread(Runnable target)
E.g: SecondThread st= new SecondThread();
Thread t=new Thread(st);

4. Thread(Runnable target, String name)


           
E.g: SecondThread st=new SecondThread();
Thread t= new Thread(st, ”Secondchild”);
Determining when a Thread ends

In java, isAlive() and join() are two different methods to check


whether a thread has finished its execution.
isAlive() :
• This method tests if the thread is alive.
• A thread is alive if it has been started and has not yet died.
join():
• This method waits for thread to die.
• It causes currently running thread to stop executing until the
thread it joins complete its task.
Example
public class ThreadDemo extends Thread
public class ThreadDemo extends Thread
{
{ public void run()
public void run() {
{ System.out.println("status = " + isAlive());
// tests if this thread is alive }
System.out.println("status = " + isAlive()); public static void main(String args[])
} throws Exception
public static void main(String args[]) throws {
Exception ThreadDemo th=new ThreadDemo ();
{ th.start();
ThreadDemo t=new ThreadDemo (); try{
t.start(); th.join();
System.out.println("status = " + t.isAlive()); }
catch(Exception e) {}
}
System.out.println("status = " + th.isAlive());
}
}
}
Join()
Thread ( ) Constructors
Thread(String name)
Thread(Runnable target)
Thread
Thread Priorities
Get and Set Thread Priority

• public final int getPriority()

 This method returns priority of given thread.

• public final void setPriority(int newPriority)

 This method changes the priority of thread to the value newPriority.

 This method throws IllegalArgumentException if value of parameter newPriority


goes beyond minimum(1) and maximum(10) limit.
Example
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.start();
m2.start();
}
}
Synchronization
• 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.
• Synchronization used to solve data inconsistency.
• Synchronization is a mechanism to ensure that a resource is shared by
one thread at a time.
Eg: When one thread is writing to a file, a second thread must be
prevented from doing so at the same time
• Key to synchronization in java is the concept of monitor.
• A monitor is an object that is used as a lock. Only one thread can own
a monitor at a given time.
• All objects in java have a monitor object by default. Thus all object
supports synchronization.
• When a thread enters into the monitor all other threads attempting to
enter the locked monitor will be suspended until the first thread exits
the monitor.
Synchronization
•If we do not use syncronization, and let two or more threads access a
shared resource at the same time, it will lead to distorted results.

•Consider an example, Suppose we have two different threads T1 and T2,


T1 starts execution and save certain values in a file temporary.txt which
will be used to calculate some result when T1 returns.

• Meanwhile, T2 starts and before T1 returns, T2 change the values saved


by T1 in the file temporary.txt (temporary.txt is the shared resource).
Now obviously T1 will return wrong result.

•To prevent such problems, synchronization was introduced. With


synchronization in above case, once T1 starts using temporary.txt file, this
file will be locked(LOCK mode), and no other thread will be able to
access or modify it until T1 returns.
How to implement Synchronization
 Synchronization can be achieved in two ways by using
1) Synchronized methods
2) Synchronized statements/Block
 These two ways use the keyword synchronized keyword to
implement synchronization
Without Synchronization
Synchronization
Synchronization Example 2
Inter thread communication
Java Support interthread communication through keywords wait(),notify(),
notifyAll().
Interthread communication:wait()
Wait general forms:
1. final void wait() throws InterruptedException
2.final void wait(long miilis) throws InterruptedException
3.final wait(long millis,long nanos) throws InterruptedException

• The first form waits until it is notified


• The second form waits unitl it is notified or until the specified period of
milliseconds has expired.
• The third form allows you to specify the wait period in terms of
milliseconds and nanoseconds.
Interthread communication:
notify(),notifyAll()
Java Support interthread communication through keywords wait(),notify(),
notifyAll().
General form of notify() and notifyAll():
1.final void notify()
2. final void notifyAll()

A call to notify() resumes one waiting thread.


A call to notifyAll() notifies all threads, with the highest priority thread
gaining access to the object.
Example
Producer consumer problem
• 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( ).
• notify( ) wakes up a thread that called wait( )
on the same object.
• notifyAll( ) wakes up all the threads that called
wait( ) on the same object. One of the threads
will be granted access.
Producer consumer problem
• Problem
To make sure that the producer won’t try to add data into the
buffer if it’s full and that the consumer won’t try to remove
data from an empty buffer.
• Solution 
The producer is to either go to sleep or discard data if the
buffer is full. The next time the consumer removes an item
from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if
it finds the buffer to be empty. The next time the producer puts
data into the buffer, it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both
processes are waiting to be awakened.
Producer consumer problem
• Inside get( ), wait( ) is called. This causes its
execution to suspend until the Producer notifies you
that some data is ready.
• When this happens, execution inside get( ) resumes.
• After the data has been obtained, get( ) calls notify( ).
This tells Producer that it is okay to put more data in
the queue.
• Inside put( ), wait( ) suspends execution until the
Consumer has removed the item from the queue.
When execution resumes, the next item of data is put in
the queue, and notify( ) is called. This tells the
Consumer that it should now remove it.
Producer consumer problem
• This program consists of four classes:
• Q, the queue that you're trying to synchronize;
• Producer, the threaded object that is producing queue entries;
• Consumer, the threaded object that is consuming queue
entries; and
• PC, the tiny class that creates the single Q, Producer, and
Consumer.
Producer consumer problem
class Q
{
int n; synchronized void put(int n)
boolean valueSet = false; {
synchronized int get() if(valueSet)
{ try
if(!valueSet) {
try wait();
{ } catch(InterruptedException e)
wait(); {
} catch(InterruptedException e) System.out.println("InterruptedException caught");
}
{
System.out.println("InterruptedException caught"); this.n = n;
} valueSet = true;
System.out.println("Got: " + n); System.out.println("Put: " + n);
valueSet = false; notify();
notify(); }
return n; }
}
Producer consumer problem
class Producer implements Runnable
class Consumer implements Runnable
{
{
Q q; Q q;
Producer(Q q) Consumer(Q q)
{ {
this.q = q; this.q = q;
new Thread(this, "Producer").start(); new Thread(this, "Consumer").start();
} }
public void run()
public void run()
{
{ while(true)
int i = 0; {
while(true) q.get();
{ }
q.put(i++); }
} }
}
}
Producer consumer problem
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Simple producer class CubbyHole {
private int contents;
consumer program private boolean available = false;
public synchronized int get() {
while (available == false) {
public class ProducerConsumerTest {
try {
public static void main(String[] wait();
args) { } catch (InterruptedException e) {}
CubbyHole c = new }
CubbyHole(); available = false;
notifyAll();
Producer p1 = new Producer(c, return contents;
1); }
Consumer c1 = new Consumer(c, public synchronized void put(int value) {
1); while (available == true) {
try {
p1.start();
wait();
c1.start(); } catch (InterruptedException e) { }
} }
} contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread { class Producer extends Thread {
private CubbyHole cubbyhole; private CubbyHole cubbyhole;
private int number; private int number;
public Producer(CubbyHole c, int number)
public Consumer(CubbyHole c, int {
number) { cubbyhole = c;
cubbyhole = c; this.number = number;
this.number = number; }
} public void run() {
public void run() { for (int i = 0; i < 10; i++) {
int value = 0; cubbyhole.put(i);
for (int i = 0; i < 10; i++) { System.out.println("Producer #" +
value = cubbyhole.get(); this.number + " put: " + i);
System.out.println("Consumer try {
#" + this.number + " got: " +
value); sleep((int)(Math.random() * 100));
} } catch (InterruptedException e) { }
} }
} }
}
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Deadlock
Deadlock in java is a part of
multithreading. Deadlock can occur in a
situation when a thread is waiting for an object
lock, that is acquired by another thread and
second thread is waiting for an object lock that
is acquired by first thread.
Thank You!!!

You might also like