Mutli Threading
Mutli Threading
txt
==============
Multi Threading
==============
Task : Work
Single Tasking : Performing only one task at a time is called as Single Tasking
Ex:
-> If we perform single tasking then it will take lot of time to complete all our work.
Ex:
Ex: Windows OS
-> To execute our program logics paralelly then we need to go for Thread Based Multi Tasking
-> Using Thread Based Multi Tasking our program can complete the work quickly
-> To implement Thread Based Multi Tasking we will use Multi Threading
=============================
Use case to go for Multi Threading
=============================
Note: The main aim of Multi Tasking is used execute our program logic paralelly so that we can
complete more work in less time.
-> For Every Java program execution, JVM will create one thread by default. That thread is called
as Main thread.
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 1/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
}
}
Note: Thread is a predefined class available in java.lang package. In Thread class we have a
static method currentThread ( ).
===================
User Defined Threads
===================
==================================================================================================
Q) What is the difference between extending Thread class and implementing Runnable interface,
which is recommended ?
==================================================================================================
-> If we extend properties from Thread class then we can't extend properties from any other class
because java doesn't support mulitple inheritence. (We are closing gate for Inheritence)
-> If we implement Runnable interface then in future we can extend properties from any class based
on requirement. (Our gate is open for inheritence)
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 2/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
=======================
What is Thread Schedular
=======================
-> Thread Schedular is a program in the JVM which is responsible to schedule Threads execution and
resources allocation required for the thread.
-> When we call start ( ) method then Thread Schedular will start its operation.
1) Allocating Resources
2) Thread Scheduling
================================
start ( ) method vs run ( ) method
================================
t.start ( )
-> once start ( ) method is called then Thread Schedular will come into picture to execute our
thread
-> inside run ( ) method we will write the logic which should be executed by the thread.
=======================================================
Can we call run ( ) method directley without calling start ( ) method
========================================================
-> Yes, we can call run ( ) method directley but it will execute like a normal method (there is no
use) by "main" thread.
-> If we want to execute run ( ) method as a thread method then we should call start ( ) method
then internally it will call run ( ) method (Thread Schedular will take care of thread execution)
Thread t = Thread.currentThread();
System.out.println(t.getName());
=> If we call start ( ) method then run ( ) method will be executed by our user defined thread (we
can see thread name as Thread-0)
=> if we call run ( ) method then run ( ) method will be executed by "main" thread (we can see
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 3/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
======================
What is Thread Life Cycle
======================
1) New
2) Runnable
3) Running
4) Blocked
5) Terminated
New: A thread begins its life cycle in the new state. Thread remains in the new state until we
will call start ( ) method.
Runnable : After calling start ( ) method, thread comes from new state to runnable state.
Running : A thread comes to running state when Thread Schedular will pick up that thread for
execution.
Blocked : A thread is in waiting state if it waits for another thread to complete its task.
Terminated : A thread enters into terminated state once it completes its task.
package in.ashokit;
try {
Thread.sleep(5000); // blocked state
} catch (InterruptedException e) {
e.printStackTrace();
}
package in.ashokit;
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 4/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
t1.start();
t1.start(); // java.lang.IllegalThreadStateException
}
=================
Callable Interface
=================
Syntax:
====================================================
What is the difference between Runnable & Callable interfaces
====================================================
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 5/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
==============================
ExecutorService
==============================
-> ExecutorService will re-use threads available in the pool to complete all submitted tasks.
package in.ashokit;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
=============
Daemon Thread
=============
3) Daemon Threads
Note: The thread which runs in the background is called as Dameon Thread. Daemon Threads also
called as low priority threads.
-> We can make our thread as Daemon Thread using setDaemon( ) method
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 6/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
package in.ashokit;
@Override
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon Thread Executed...");
} else {
System.out.println("Normal Thread Executed...");
}
-> When JVM reaches end of main method, it will terminate our program. If JVM founds Daemon thread
running it terminates that daemon thread and then it will shutdown the program.
-> JVM will not care about Daemon Threads running status to stop the program execution.
==============
Synchronization
==============
StringBuffer ----> Mutable class & synchronized class (Thread safe class)
StringBuilder ---> Mutable class & not-synchronized class (Not Thread Safe class)
Synchronized means Thread safe ===> Only one thread can access the object / resource at a time
Not-Synchronized means Not Thread Safe => Multiple threads can access same resource / object at
a time
psvm ( ) {
Thread t1 = new Thread();
Thread t2 = new Thread();
Threa t20 = new Thread();
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 7/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
-> In the program, multiple threads are trying to book tickets at a time
Note: If multiple threads access the same object at a time then there is a chance of getting data
inconsistency problem.
=> Synchronization means allowing only one thread to execute our resource / object / logic at a
time
Note: By Using Synchronization we can achieve Thread Safety but it will slow down our execution
process.
===========================
How to achieve synchronization
===========================
1) At method level
2) At block level
--------------------------------------------
Syntax For Synchronized Block:
--------------------------------------------
// pre-logic
synchronized ( object ) {
// imp business logic
}
// post-logic
--------------------------------------------
Syntax For Synchronized Method :
--------------------------------------------
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 8/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
}
}
Note: In the above program we are starting 2 threads. two threads will access printNums ( ) method
to print the numbers from 1 to 10.
-> If printNums ( ) method having synchronized keyword then two threads will execute the method
sequentially one after other .
-> if we remove synchronized keyword from the printNums ( ) method then two threads will access
that method at a time.
==============================================
Working with Threads using Anonymous Implementation
==============================================
package in.ashokit;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 9/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
==========
Dead Lock
=========
-> If 2 threads are waiting for each other to release the resources is called as dead lock.
-> Once we get into dead lock situation then we can't do anything
Ex:
----
Note:
Thread-1 will not release resource-1 hence thread-2 will be in waiting state forever for resource-
1
Thread-2 will not release resource-2 hence thread-1 will be in waiting state forever for resource-
2
package in.ashokit;
String s1 = "hi";
String s2 = "hello";
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 10/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
e.printStackTrace();
}
synchronized (s1) {
System.out.println("Thread-2 waiting for resource-
1");
}
}
}
};
t1.start();
t2.start();
}
}
=============
join ( ) method
=============
-> join ( ) method is used to hold second thread execution until first thread execution got
completed
package in.ashokit;
t1.start();
t1.join();
t2.start();
}
}
==============
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 11/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
yield ( ) method
===============
-> yield ( ) method is used to give chance for other equal priority threads to execute
package in.ashokit;
producer.start();
consumer.start();
}
}
========================
Inter Thread Communication
========================
-> To achieve inter thread communication we have below 3 methods in Object class
1) wait ( )
2) notify ( )
3) notifyAll ( )
Q) Why these 3 methods available in Object class, why not in Thread class ?
-> If these methods available in Thread class then we have to extend Thread class. In future we
can't extend from any other java class bcz java is against for Multiple Inheritence.
-> If these methods available in Runnable interface then everybody should implement these method
even if they don't need inter thread communication.
-> To overcome all these problems, java kept these methods in Object class so that every class
will have access for these methods.
package in.ashokit;
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 12/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
new Thread() {
public void run() {
c.withdraw(15000);
}
}.start();
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread() {
public void run() {
c.deposit(10000);
}
}.start();
}
}
================================
Multi Threading Summary
=================================
1) What is Multi Tasking
2) What is Multi Threading
3) Advantages of Multi Threading
4) Default Thread in JVM (main)
5) Getting info of main thread ( Thread.currentThread( ) )
6) Creating User Defined Threads
7) By Extending Thread class
8) By Implementing Runnable interface
9) By implementing Callable interface
10) run ( ) method vs call ( )
11) Executor Service
12) run ( ) vs start ( ) method
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 13/14
5/9/23, 10:46 AM https://ashokitech.com/uploads/notes/669433580_1669991443.txt
https://ashokitech.com/uploads/notes/669433580_1669991443.txt 14/14