Multithreading
Multithreading
_________________________________________________________________________
Q. what is multi threading?
____________________________________________________________
Before multi threading we need to know
Q. what is thread?
______________________________________________________________________
Thread is sub part of process or it is light weight process.
Q. what is process?
Process means current running application or program in ram called as process.
Note: Threading is concept of operating system and java is language which provides implementation to
thread concept.
Internally structure
interface Runnabe{
public void run();
}
class Thread implements Runnable{
}
class MyThread extends Thread{
}
Sample code
___________________________________________________________________
class MyThread extends Thread{
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First Thread is "+i);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
4. Create object of thread child class
____________________________________________________________________
As per our example of MyThread is child of Thread class.
Sample code
package org.techhub;
class MyThread extends Thread{
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First Thread is "+i);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
public class MyThreadApplication {
public static void main(String[] args) {
MyThread m = new MyThread();
}
}
5. Use its method to manage the thread
____________________________________________________________________
If we want to work with thread we have some inbuilt method of Thread class given below.
void start(): this method is used for start the thread means when we call this method or call start()
method, internally run() method of thread class get executed.
public static void sleep(int milliseconds): this method is used for hold thread execution for specified
time period and re-execute thread after some specified time period
package org.techhub;
class MyThread extends Thread{
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First Thread is "+i);
Thread.sleep(10000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Second extends Thread{
public void run() {
try {
for(int i=1; i<=50;i++) {
System.out.printf("Second thread is %d\n",i);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
public class MyThreadApplication {
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
Note: if we think about above code we have two threads name as First and Second and when we call
start() method with First thread then run() method of first get executed internally and First thread get
executed and wait for 10 seconds so processor start second thread within that period and execute it 10
times because second thread has 1 second waiting and after execute second thread 10 times again
processor execute first thread in 1 second waiting of second and again execute second 10 times
means here processor utilize the waiting period of first thread for execute second thread and waiting of
second execute first simultaneously called as multi threading
If we want to execute only first thread completely if he has waiting period and start execution of second
thread after first thread then we have one more method name as join()
public void join(): this method can hold thread execution for specified time period when ever running
thread is not completed. If we call join() method on some thread then first it will executed and
terminated till that point and then next execution will goes on.
e.g
class Mythread1 extends Thread{
public void run() {
try{
Thread.sleep(5000);
}
catch(Exception ex) {
System.out.println("Error is : " + ex);
}
System.out.println(“Mythread terminated”);
}
}
public class first {
}
Output :
Mythread terminated
Main thread Terminated
Note: when we call the join () then we need to handle the InterruptedExceptions.
public boolean isAlive(): this method can check status of thread means thread is running or not if thread
is running return true otherwise return false.
public void stop(): this method can terminate the thread execution
Note: we have some more method we will discuss later in this chapter.
Example:
package org.techhub;
class MyThread extends Thread{
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("First Thread is "+i+"\t"+isAlive());
if(i==3) {
stop();
}
Thread.sleep(10000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Second extends Thread{
public void run() {
try {
for(int i=1; i<=50;i++) {
System.out.printf("Second thread is %d\n",i);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
public class MyThreadApplication {
public static void main(String[] args)throws InterruptedException {
MyThread m = new MyThread();
m.start();
m.join();
System.out.println("Now Status of First Thread "+m.isAlive());
Second s = new Second();
s.start();
}
}
Example of Asynchronization
package org.techhub;
class Table
{
public void showTable(int x) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,x,i*x);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Two extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t = new Table();
Two tw = new Two();
tw.setTable(t);
tw.start();
Three th = new Three();
th.setTable(t);
th.start();
}
}
Example of Synchronization
package org.techhub;
class Table
{
public synchronized void showTable(int x) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,x,i*x);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Two extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t = new Table();
Two tw = new Two();
tw.setTable(t);
tw.start();
Three th = new Three();
th.setTable(t);
th.start();
}
}
Inter Thread Communication
wait(),notify() and notifyAll() methods
_____________________________________________________________________________
wait () method is used for hold the thread execution for specified time period
There are two types of wait
1. Conditional wait : conditional wait() means if we hold the thread execution for specified time period
and thread re-execute after that called as conditional wait.
Syntax: void wait(int milliseconds): this method is used for hold thread execution for specified time
period.
2. Unconditional wait : unconditional wait means if we hold the execution and thread not re-execute
after some specified time period called as unconditional wait and in the case of unconditional wait we
need to send request to thread for re-execution purpose and for that we have two methods
void notify() and void notifyAll()
void notify(): this method can call unconditional waited thread and call only one thread at time in first in
first out format. Doesn’t Work Properly
void notifyAll(): this method can call waited thread at time in last in first out format.
import java.util.*;
class Table
{
public synchronized void showTable(int x) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,x,i*x);
if(i==5) {
wait();
}
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
public synchronized void recall() {
try {
notifyAll();
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Two extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t = new Table();
Two tw = new Two();
tw.setTable(t);
tw.start();
Three th = new Three();
th.setTable(t);
th.start();
do {
Scanner xyz = new Scanner(System.in);
String msg=xyz.nextLine();
if(msg.equals("restart"))
{
t.recall();
}
}while(true);//infinite loop
}
}
Q. what is diff between wait() and sleep() method?
_______________________________________________________________________
2. Synchronization:
sleep():
sleep() does not require the thread to hold any lock.
It is usually used when you want the thread to pause execution for a specific time.
wait():
wait() must be called from a synchronized context, meaning the thread must hold the object's
monitor (lock) before calling wait().
It is used in scenarios where one thread needs to wait for a specific condition to be met (like a
resource becoming available) before it can continue execution.
3. Releasing Locks:
sleep():
o The thread does not release any locks when it goes to sleep. Other threads waiting for
the same lock will continue to be blocked.
wait():
o The thread releases the lock on the object when it calls wait(), allowing other threads to
acquire the lock and proceed. The waiting thread will remain blocked until another
thread invokes notify() or notifyAll() on the same object.
4. Resumption:
sleep():
o The thread will automatically resume after the specified sleep duration without needing
any external trigger.
wait():
o The thread will only resume when another thread calls notify() or notifyAll() on the same
object or when it is interrupted.
5. Typical Use Cases:
sleep():
o Used to delay execution or simulate a delay, such as polling, timeouts, or simply
delaying execution for a fixed amount of time.
wait():
o Used in producer-consumer problems, or any situation where threads need to
communicate and coordinate with each other. For example, a producer thread might
wait if a buffer is full, and a consumer thread would notify the producer when there is
space available in the buffer.
Thread priority
__________________________________________________________________________________
Thread priority means decide the starting or execution priority of thread called as thread priority.
if we think about priority of thread in JAVA we have some inbuilt fix constant values declared within
Thread class
class Thread{
public static final int MAX_PRIORITY=10;
public static final int MIN_PRIORITY=1;
public static final int NORM_PRIORITY=5;
}
So if we want to use any priority of thread we can use it like as Thread.MAX_PRIORITY
If we want to apply priority on thread we have inbuilt method name as
void setPriority(int priority): this method is used for set the priority on thread
int getPriority(): this method can return the priority of thread and the default priority on thread is
normal priority means 5
Example:
package org.techhub;
import java.util.*;
class Table
{
public synchronized void showTable(int x) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,x,i*x);
if(i==5) {
wait();
}
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
public synchronized void recall() {
try {
notifyAll();
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
class Two extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
public void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t = new Table();
Two tw = new Two();
tw.setTable(t);
Three th = new Three();
th.setTable(t);
th.setPriority(Thread.MAX_PRIORITY);
tw.setPriority(Thread.MIN_PRIORITY);
tw.start();
th.start();
do {
Scanner xyz = new Scanner(System.in);
String msg=xyz.nextLine();
if(msg.equals("restart"))
{
t.recall();
}
}while(true);//infinite loop
}
}
Daemon thread: Daemon thread means service provider thread they work as background
thread in java like as garbage collector is best example of daemon thread.
Note: user can mark own thread as daemon thread and for that we have methods.
void setDaemon(boolean): this method is used for set thread as daemon thread if we pass true value in
it
boolean isDaemon(): this method is used for check user thread is daemon thread or not.
Note :
1] Q. Which is better Thread class to extend or Runnable Interface to implement?
Ans : When we have to extend only Thread class and not any other class then we can use Thread class
but if we want to extend any other class then we should use Runnable Interface because if we try to
extend two classes then it is not possible in java
e.g
class A{
}
Class B extends Thread, A{
}
This is not possible because we can do multiple inheritance in Java as it creates Diamond Problem
If we do like this
Class B extends A implements Runnable{
}
In this way we extend A class and also use threading by using Runnable Interface
}
}
public class RunnableInterApp {