Multithreding v1
Multithreding v1
Java
Multithreding
Introduction
@techwithvishalraj
Multitasking
Multitasking is a process of executing multiple tasks simultaneously.
We use multitasking to utilize the CPU. Multitasking can be achieved
in two ways:
Program:
A program is an executable file containing a set of instructions
passively stored on disk.
Process:
A process is a program in 𝐞𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧.
When a program is loaded into the memory and becomes active,
the program becomes a process.
A process requires some essential resources such including CPU
time, program counter, stack, memory, files, and I/O devices — to
accomplish its task.
Program is a 𝐩𝐚𝐬𝐬𝐢𝐯𝐞 entity while process is an 𝐚𝐜𝐭𝐢𝐯𝐞 entity.
One program can have 𝐦𝐮𝐥𝐭𝐢𝐩𝐥𝐞 processes.
Thread :
A 𝐓𝐡𝐫𝐞𝐚𝐝 is the smallest unit of execution within a process (or)
basically it is a segment of a process .
Thread is also known as lightweight process.
There are two types of processes :
1. 𝐒𝐢𝐧𝐠𝐥𝐞 𝐓𝐡𝐫𝐞𝐚𝐝𝐞𝐝 𝐏𝐫𝐨𝐜𝐞𝐬𝐬
2. 𝐌𝐮𝐥𝐭𝐢 Threaded Process
@techwithvishalraj
Threads
TID - Thread id
Instruction 1
Disk
Instruction 2
Instruction 3
Program
......
Instruction n
RAM
Stack
Stack Stack Stack
Output:
i= 0
class CustomThread extends Thread { i= 1
public void run() { i= 0
for (int i = 0; i < 10; i++) { i= 1
System.out.println("i= " + i); i= 2
} i= 3
} i= 2
} i= 4
public class ByExtendingThreadClass { i= 5
public static void main(String[] args) { i= 6
CustomThread t1 = new CustomThread(); i= 7
t1.setName("CustomThread"); i= 3
t1.start(); i= 4
CustomThread t2 = new CustomThread(); i= 8
t2.start(); i= 9
} i= 5
} i= 6
i= 7
i= 8
i= 9
2. By Implementing the Runnable Interface @techwithvishalraj
If you are not extending the Thread class, your class object would
not be treated as a thread object. So you need to explicitly create
the Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.
Output:
i= 0
class CustomRunnable implements Runnable{
i= 1
public void run() {
i= 0
for (int i = 0; i < 10; i++) {
i= 1
System.out.println("i= " + i);
i= 2
}
i= 3
}
i= 2
}
i= 4
public class ByImplementingRunnableInterface {
i= 5
public static void main(String[] args) {
i= 6
Thread t1 =new Thread(new CustomRunnable());
i= 7
t1.start();
i= 3
Thread t2 =new Thread(new CustomRunnable());
i= 4
t2.start();
i= 8
}
i= 9
}
i= 5
i= 6
i= 7
i= 8
i= 9
@techwithvishalraj
Thank
you!
vishal-bramhankar
techwithvishalraj
Vishall0317