0% found this document useful (0 votes)
7 views

Multithreading

Multithreading in java pdf

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Multithreading

Multithreading in java pdf

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

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.

Q. what is multi threading?


__________________________________________________________________
Multi threading means if more than one thread execute simultaneously in waiting of each other
called as multi threading.
Means in short we say multi threading means to utilize the idle period of processor.

Note: Threading is concept of operating system and java is language which provides implementation to
thread concept.

If we want to implement thread practically in Java we have two ways.


1. by using Thread class
2. By using Runnable interface

How to create thread using Thread class


__________________________________________________________________
Steps to create thread using Thread class.
1. Add java.lang package in application
_______________________________________________________________
The Thread class in Java is part of the java.lang package. This package is automatically imported by
the Java compiler for every Java program, so you do not need to explicitly import it.

2. Create User defined class and inherit Thread class in it


_______________________________________________________________________
If we want to create thread in java we have to create own user define class and inherit thread class in it.

class MyThread extends Thread{


}
Note: Here we can say MyThread is user define class and Thread is inbuilt class from java.lang package
and we can inherit the all properties from Thread class in MyThread Means we can say MyThread is
thread.

3. Override its run() method and write thread logics


____________________________________________________________________________
If we think about run() method it is original member of Runnable interface and Runnable is a interface
from java.lang package and it is implemented in Thread class internally so you can use run() method of
Runnable by using Thread class.

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();

Second s = new Second();


s.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 {

public static void main(String[] args) throws


InterruptedException {
Mythread1 m = new Mythread1();
m.start();

m.join(); // due to this join() method compiler


wait until thread m get terminated

System.out.println(“Main thread Terminated”);

}
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();
}
}

Synchronization and Asynchronization of Thread


__________________________________________________________________________
Synchronization means if two or more than two thread use single resource/object sequentially one by
one called as synchronization.
Asynchronization means if two or more than two thread use the single resource/object simultaneously
called as asynchornization.
Example: we want to design Table with method void showTable(int x) and we have two thread
name as Two and Three and we want to share the reference of Table class in both threads
and print table 2 and 3 table

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.

Note: wait(),notify() and notifyAll() methods of Object class.

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?
_______________________________________________________________________

Wait method Sleep method


Wait method is member of java.lang.Object class Sleep() method is member of java.lang.Thread
class
Wait() method can work with conditional as well Sleep() method can only work with conditional
as unconditional wait wait
Wait() method can only work in synchronized Sleep() method can work in synchronized as well
block as asynchronized block

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.

Q.what is diff beween notify() and notifyAll() method?


notify() method is used for call waited thread in first in first out manner and call only one thread at time
and notifyAll() method can call all waited thread in last in first out format.

Thread priority
__________________________________________________________________________________
Thread priority means decide the starting or execution priority of thread called as thread priority.

There are three types of Thread priority


______________________________________________________________________________
1. MAX PRIORITY: MAX PRIORITY it is highest priority of thread and the default value max priority is 10
2. MIN PRIORITY : MIN priority is lower priority of thread and the default value of min priority is 1
3. NORM_PRIORITY: normal priority is default priority thread and it has default value 5

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
}
}

Note: you cannot use any program in java without thread.


Because in java program we have one default thread name as main thread and it has default priority 5
i.e normal priority.
package org.techhub;
public class SyncAsyncApplication {
public static void main(String[] args) {
Thread t=Thread.currentThread();
String threadName=t.getName();
System.out.println("Thread name is "+threadName);
int priority=t.getPriority();
System.out.println("Default priority of thread "+priority);
}
}

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

2] We can create an reference of Runnable and pass object of class in it


e.g
class TATA implements Runnable{

public void run() {


for(int i=0;i<5; i++) {
System.out.println("TATA");
try{Thread.sleep(1000);}catch(Exception e)
{ e.getStackTrace();}
}

}
}
public class RunnableInterApp {

public static void main(String[] args) {

Runnable obj1 = new TATA();


Thread o1 = new Thread(obj1); // we have
created this because we can’t call start() without
Thread class object
o1.start();
}
}

You might also like