SlideShare a Scribd company logo
Programming in Java
Topic: Multi-threading
By
Ravi Kant Sahu
Asst. Professor

Lovely Professional University, Punjab
Agenda
•
•
•
•
•
•
•
•
•
•

Introduction
Process Vs Thread
Thread Life cycle
Runnable Interface
Thread class
Creating a Thread
Creating Multiple Threads
Synchronization of Threads
Inter-thread Communication
Suspending, Resuming and Stopping Threads
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• Concurrent Execution of multiple tasks is called Multitasking.

Multitasking

Multi-processing
(Process-based)

Multi-threading
(Thread-based)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• Multithreading is a specialized form of multitasking.
• A multithreaded program contains two or more parts (threads)
that can run concurrently.
• Each thread defines a separate path of execution.
• Java provides built-in support for multithreaded programming.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Process and Threads
• In concurrent programming, there are two basic units of execution:
processes and threads.

• Process: is an executable program loaded in memory
» has its own Variables & data structures (in memory)
» Communicate via operating system, files, network
» May contain multiple threads

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Threads
• A thread is an independent module of an application that can be
concurrently executed with other threads.
• Also known as “lightweight process”.
• Threads exist within a process — every process has at least one.
• Multiple threads in process execute same program.
• Threads share the process's resources, including memory and
open files.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• A thread cannot exist on its own; it must be a part of a process.
• A process remains running until all of the non-daemon threads
are done executing.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Life Cycle of a Thread
• New: The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
• Runnable: The thread is in runnable state after invocation of
start() method, but the thread scheduler has not selected it to
be the running thread.
• Running: The thread is in running state if the thread
scheduler has selected it.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• Waiting/Blocked: This is the state when the thread is still
alive, but is currently not eligible to run.
• Terminated: A thread is in terminated or dead state when its
run() method exits.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Multithreading in Java
• In order to achieve multithreading in java application,
java.lang.Runnable interface is provided.
• java.lang.Thread class is provided as part of core java library
which provides methods that are used to:
– start and suspend a thread
– obtain the state of a thread
– change the state of a thread

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Runnable Interface
• Runnable interface contains a single method run().
public interface Runnable
{
public void run();
}
• Inside run( ), we will define the code that constitutes the new
thread.
• run( ) can call other methods, use other classes, and declare
variables.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Thread Class
• Thread class provides methods to start a thread, suspend a
thread and obtain the state of a thread.
public class Thread {
public Thread(Runnable R); // Thread ⇒ R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• currentThread(): used to obtain the reference of thread
object for the current thread.
public static Thread currentThread()

• getName(): returns the name of the thread.
public String getName()

• setName(): used to change the name of a thread.
public void setName(String Name)

• getPriority(): used to obtain the priority of thread.
public int getPriority()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• start(): used to start the execution of a thread.
public void start()

• sleep(): is used to suspend the current thread for the specified time.
public static void sleep(long milliseconds) throws InterruptedException

• isAlive(): used to find out whether a thread is completed or not .
public boolean isAlive()

• static void yield(): This method causes the currently executing
thread object to temporarily pause and allow other threads to execute.

• void join(): Waits for this thread to die.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating Threads in Java
• A user thread is represented by run().
• There are two ways of defining a thread:
– By extending Thread class
– By implementing Runnable interface
Runnable

Runnable

Thread
MyThread

MyThread

• The first case is not recommended because our class may already
have a super class, so we can not extend another class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Implementing Runnable
• We can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement run( ).
• Inside run( ), we will define the code that constitutes the new thread.
• run( ) can call other methods, use other classes, and declare variables,
just like the main thread can.
• The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within our program.
• This thread will end when run( ) returns.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class MyThread implements Runnable
{
Thread t;
MyThread()
{
t = new Thread(this, "My Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run()
{
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class ThreadDemo1
{
public static void main(String args[])
{
new MyThread();
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Extending Thread Class
• The second way to create a thread is to create a new class that
extends Thread.
• Create an instance of that class.
• Override the run( ) method.
• Call start( ) to begin execution of the new thread.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class MyThread1 extends Thread {
MyThread1() {
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); }
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500); }
}
catch (InterruptedException e) {
System.out.println("Child interrupted."); }
System.out.println("Exiting child thread.");
}
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class ExtendThread {
public static void main(String args[]) {
new MyThread1();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating Multiple Threads
class MultiThreadDemo
{
public static void main(String args[]) {
new MyThread2("One");
new MyThread2("Two");
new MyThread2("Three");
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class MyThread2 implements Runnable {
String name; Thread t;
MyThread2(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); }
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Notice the call to sleep(10000) in main( ).
• This causes the main thread to sleep for ten seconds and ensures that
it will finish last.
• Two ways exist to determine whether a thread has finished.
• Call isAlive( ) on the thread.
final boolean isAlive( )
• Call join( ) on thread.
final void join( ) throws InterruptedException
• This method waits until the thread on which it is called terminates.
• Additional forms of join( ) allow to specify a maximum amount of
time that you want to wait for the specified thread to terminate.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Synchronization
• Race Condition: Multiple threads calling the same method, on
the same object, at the same time.
• 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 is achieved is called synchronization.
• Monitor (Semaphore) is used for synchronization.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Monitor
• A 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.
• All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.
• These other threads are said to be waiting for the monitor.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Need of Synchronization: Example
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try {
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using Synchronized Methods
• Methods qualified with synchronized keyword are called
Synchronized Methods.
• While a thread is inside a synchronized method, all other threads
that try to call it (or any other synchronized method) on the same
instance have to wait.
• To exit the monitor and relinquish control of the object to the
next waiting thread, the owner of the monitor simply returns
from the synchronized method.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using Synchronized Methods
• A synchronized method can be executed by only one thread at a
time.
Example: Synch.java and Synch1.java

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Synchronized Method: Example
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try {
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
The synchronized Statement
• A synchronized block ensures that a call to a method occurs only
after the current thread has successfully entered object’s monitor.
• put calls to the methods defined by the class inside a
synchronized block.
synchronized(object)
{
// statements to be synchronized
}
• Here, object is a reference to the object being synchronized.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Synchronized Statement: Example
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{ // synchronized block
target.call(msg);
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
}
}
Suspending, Resuming, and Stopping Threads
• Execution of a thread can be suspended.
• Restarting the execution of a suspended thread is also possible.
• Prior to Java 2, suspend( ) and resume( ) methods (defined by
Thread), were used to pause and restart the execution of a thread.
final void suspend( )
final void resume( )
• The Thread class also defines a method called stop( ) that stops a thread.
final void stop( )
• Once a thread has been stopped, it cannot be restarted using resume( ).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• suspend( ), resume( ), and stop( ) methods defined by Thread were
deprecated by Java2.

Why???
• suspend( ) can sometimes cause serious system failures as in case
of locking.
• resume() is deprecated because it cannot be used without the
suspend( ).
• stop( ) can also cause serious system failures so it was also
deprecated.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Now how to
suspend, resume and stop
a thread?
New Approach for suspending, resuming and
stopping a thread
• A thread must be designed so that the run( ) method periodically
checks to determine whether that thread should suspend, resume, or
stop its own execution.
• This is accomplished by establishing a flag variable that indicates the
execution state of the thread.
– As long as this flag is set to “running,” the run( ) method must continue to let
the thread execute.
– If this variable is set to “suspend,” the thread must pause.
– If it is set to “stop,” the thread must terminate.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class NewThread implements Runnable
{
NewThread(String threadname) {}
public void run() {}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class SuspendResume
{
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
•

wait( ) and notify( ) methods are inherited from Object class can be used to
control the execution of a thread.

•

The NewThread class contains a boolean instance variable named
suspendFlag, which is used to control the execution of the thread.

•

It is initialized to false by the constructor.

•

The run( ) method contains a synchronized statement block that checks
suspendFlag.

•

If that variable is true, the wait( ) method is invoked to suspend the execution
of the thread.

•

The mysuspend( ) method sets suspendFlag to true.

•

The myresume( ) method sets suspendFlag to false and invokes notify( ) to
wake up the thread.

•

Finally, the main( ) method has been modified to invoke the mysuspend( )
and myresume( ) methods.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inter-thread Communication
• wait( ), notify( ), and notifyAll( ) methods are used for
communication among threads.
• All three methods can be called only from within a synchronized
context.
• 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inter-thread Communication
• These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

More Related Content

What's hot

12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
suraj pandey
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in javaAbhra Basak
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 

What's hot (20)

12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Threads
ThreadsThreads
Threads
 
Swing api
Swing apiSwing api
Swing api
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 

Viewers also liked

Sms several papers
Sms several papersSms several papers
Sms several papersArjun Shanka
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
Saloni Jaiswal
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in JavaRavi_Kant_Sahu
 

Viewers also liked (12)

Basic IO
Basic IOBasic IO
Basic IO
 
List classes
List classesList classes
List classes
 
Packages
PackagesPackages
Packages
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Event handling
Event handlingEvent handling
Event handling
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Servlets
ServletsServlets
Servlets
 
Jdbc
JdbcJdbc
Jdbc
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Generics
GenericsGenerics
Generics
 

Similar to Multi threading

7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
SivaSankari36
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
Raheemaparveen
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructorsRavi_Kant_Sahu
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Java threads
Java threadsJava threads
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 

Similar to Multi threading (20)

7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Java keywords
Java keywordsJava keywords
Java keywords
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java threads
Java threadsJava threads
Java threads
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 

Multi threading

  • 1. Programming in Java Topic: Multi-threading By Ravi Kant Sahu Asst. Professor Lovely Professional University, Punjab
  • 2. Agenda • • • • • • • • • • Introduction Process Vs Thread Thread Life cycle Runnable Interface Thread class Creating a Thread Creating Multiple Threads Synchronization of Threads Inter-thread Communication Suspending, Resuming and Stopping Threads Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Introduction • Concurrent Execution of multiple tasks is called Multitasking. Multitasking Multi-processing (Process-based) Multi-threading (Thread-based) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Introduction • Multithreading is a specialized form of multitasking. • A multithreaded program contains two or more parts (threads) that can run concurrently. • Each thread defines a separate path of execution. • Java provides built-in support for multithreaded programming. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Process and Threads • In concurrent programming, there are two basic units of execution: processes and threads. • Process: is an executable program loaded in memory » has its own Variables & data structures (in memory) » Communicate via operating system, files, network » May contain multiple threads Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Threads • A thread is an independent module of an application that can be concurrently executed with other threads. • Also known as “lightweight process”. • Threads exist within a process — every process has at least one. • Multiple threads in process execute same program. • Threads share the process's resources, including memory and open files. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. • A thread cannot exist on its own; it must be a part of a process. • A process remains running until all of the non-daemon threads are done executing. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Life Cycle of a Thread • New: The thread is in new state if you create an instance of Thread class but before the invocation of start() method. • Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. • Running: The thread is in running state if the thread scheduler has selected it. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. • Waiting/Blocked: This is the state when the thread is still alive, but is currently not eligible to run. • Terminated: A thread is in terminated or dead state when its run() method exits. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Multithreading in Java • In order to achieve multithreading in java application, java.lang.Runnable interface is provided. • java.lang.Thread class is provided as part of core java library which provides methods that are used to: – start and suspend a thread – obtain the state of a thread – change the state of a thread Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Runnable Interface • Runnable interface contains a single method run(). public interface Runnable { public void run(); } • Inside run( ), we will define the code that constitutes the new thread. • run( ) can call other methods, use other classes, and declare variables. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Thread Class • Thread class provides methods to start a thread, suspend a thread and obtain the state of a thread. public class Thread { public Thread(Runnable R); // Thread ⇒ R.run() public Thread(Runnable R, String name); public void start(); // begin thread execution ... } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. Methods of Thread class • currentThread(): used to obtain the reference of thread object for the current thread. public static Thread currentThread() • getName(): returns the name of the thread. public String getName() • setName(): used to change the name of a thread. public void setName(String Name) • getPriority(): used to obtain the priority of thread. public int getPriority() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Methods of Thread class • start(): used to start the execution of a thread. public void start() • sleep(): is used to suspend the current thread for the specified time. public static void sleep(long milliseconds) throws InterruptedException • isAlive(): used to find out whether a thread is completed or not . public boolean isAlive() • static void yield(): This method causes the currently executing thread object to temporarily pause and allow other threads to execute. • void join(): Waits for this thread to die. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Creating Threads in Java • A user thread is represented by run(). • There are two ways of defining a thread: – By extending Thread class – By implementing Runnable interface Runnable Runnable Thread MyThread MyThread • The first case is not recommended because our class may already have a super class, so we can not extend another class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. Implementing Runnable • We can construct a thread on any object that implements Runnable. • To implement Runnable, a class need only implement run( ). • Inside run( ), we will define the code that constitutes the new thread. • run( ) can call other methods, use other classes, and declare variables, just like the main thread can. • The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within our program. • This thread will end when run( ) returns. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. class MyThread implements Runnable { Thread t; MyThread() { t = new Thread(this, "My Thread"); System.out.println("Child thread: " + t); t.start(); } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. class ThreadDemo1 { public static void main(String args[]) { new MyThread(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. Extending Thread Class • The second way to create a thread is to create a new class that extends Thread. • Create an instance of that class. • Override the run( ) method. • Call start( ) to begin execution of the new thread. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. class MyThread1 extends Thread { MyThread1() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. class ExtendThread { public static void main(String args[]) { new MyThread1(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Creating Multiple Threads class MultiThreadDemo { public static void main(String args[]) { new MyThread2("One"); new MyThread2("Two"); new MyThread2("Three"); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. class MyThread2 implements Runnable { String name; Thread t; MyThread2(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. Notice the call to sleep(10000) in main( ). • This causes the main thread to sleep for ten seconds and ensures that it will finish last. • Two ways exist to determine whether a thread has finished. • Call isAlive( ) on the thread. final boolean isAlive( ) • Call join( ) on thread. final void join( ) throws InterruptedException • This method waits until the thread on which it is called terminates. • Additional forms of join( ) allow to specify a maximum amount of time that you want to wait for the specified thread to terminate. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. Synchronization • Race Condition: Multiple threads calling the same method, on the same object, at the same time. • 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 is achieved is called synchronization. • Monitor (Semaphore) is used for synchronization. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Monitor • A 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. • All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. • These other threads are said to be waiting for the monitor. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Need of Synchronization: Example class Callme { void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Example class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() { target.call(msg); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. Example class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. Using Synchronized Methods • Methods qualified with synchronized keyword are called Synchronized Methods. • While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. • To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. Using Synchronized Methods • A synchronized method can be executed by only one thread at a time. Example: Synch.java and Synch1.java Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 34. Synchronized Method: Example class Callme { synchronized void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 35. The synchronized Statement • A synchronized block ensures that a call to a method occurs only after the current thread has successfully entered object’s monitor. • put calls to the methods defined by the class inside a synchronized block. synchronized(object) { // statements to be synchronized } • Here, object is a reference to the object being synchronized. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. Synchronized Statement: Example class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() { synchronized(target) { // synchronized block target.call(msg); } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) } }
  • 37. Suspending, Resuming, and Stopping Threads • Execution of a thread can be suspended. • Restarting the execution of a suspended thread is also possible. • Prior to Java 2, suspend( ) and resume( ) methods (defined by Thread), were used to pause and restart the execution of a thread. final void suspend( ) final void resume( ) • The Thread class also defines a method called stop( ) that stops a thread. final void stop( ) • Once a thread has been stopped, it cannot be restarted using resume( ). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. • suspend( ), resume( ), and stop( ) methods defined by Thread were deprecated by Java2. Why??? • suspend( ) can sometimes cause serious system failures as in case of locking. • resume() is deprecated because it cannot be used without the suspend( ). • stop( ) can also cause serious system failures so it was also deprecated. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 39. Now how to suspend, resume and stop a thread?
  • 40. New Approach for suspending, resuming and stopping a thread • A thread must be designed so that the run( ) method periodically checks to determine whether that thread should suspend, resume, or stop its own execution. • This is accomplished by establishing a flag variable that indicates the execution state of the thread. – As long as this flag is set to “running,” the run( ) method must continue to let the thread execute. – If this variable is set to “suspend,” the thread must pause. – If it is set to “stop,” the thread must terminate. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 41. class NewThread implements Runnable { NewThread(String threadname) {} public void run() {} void mysuspend() { suspendFlag = true; } synchronized void myresume() { suspendFlag = false; notify(); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 42. class SuspendResume { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming thread One"); ob2.mysuspend(); System.out.println("Suspending thread Two"); Thread.sleep(1000); ob2.myresume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 43. try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 44. • wait( ) and notify( ) methods are inherited from Object class can be used to control the execution of a thread. • The NewThread class contains a boolean instance variable named suspendFlag, which is used to control the execution of the thread. • It is initialized to false by the constructor. • The run( ) method contains a synchronized statement block that checks suspendFlag. • If that variable is true, the wait( ) method is invoked to suspend the execution of the thread. • The mysuspend( ) method sets suspendFlag to true. • The myresume( ) method sets suspendFlag to false and invokes notify( ) to wake up the thread. • Finally, the main( ) method has been modified to invoke the mysuspend( ) and myresume( ) methods. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 45. Inter-thread Communication • wait( ), notify( ), and notifyAll( ) methods are used for communication among threads. • All three methods can be called only from within a synchronized context. • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 46. Inter-thread Communication • These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( ) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)