- CPU is brain of computer
- A core in a CPU is an individual processing unit
- modern CPUs have multiple cores to perform mutiple tasks simultaneously
- Program : Set of instructions
Basic Terminology
- Process
- process is a program under execcution
- process is an instance of a program
- Thread
- A thread is the smallest unit of execution within a process
- A process can have multiple threads that share the same resources but work independently
- A thread is a lightweight process, the smallest unit of processing
- MultiTasking
- Multitasking allows the OS to perform multiple processes simulatenously
- On single core Operating System , multitasking is achieved by preemption, time sharing, rapid switching between tasks etc
- On multi core CPUs , true multitasking occurs where prallel execution occours with tasks distributed across cores
- Assigning different tasks to different cores is more efficient than all to a single core.
- Multi-threading
- refers to concurrently executing multiple threads within a single process
- e.g. Browser - different threads for rendering page, running JavaScript and Managing inputs
- Multihtreading enhances the efficiency of multitasking by dividing individual tasks into subtasks and threads
- these threads can be executed simulatenously using CPU resources efficiently
- Context switching - refers to saving the current state, progress of the current process and moving to the next when current’s time slice expires
- it helps multitasking in single core CPUs and help improve parallelism in threads in multi core CPUs
Multithreading in java
- in single core systems, JVM and OS work together to share time slices among process giving illusion of parallel processing
- in multicore systems, JVM can fully utilize multiple cores for multiple threads
- Java supports multithreading through java.lang.Thread class and java.lang.Runnable interface
// using java.lang.Thread
class ApnaThreadUsingClass extends Thread{
public void run(){
system.out.println("Hi")
}
}
// using java.lang.Runnable
class ApnaThreadUsingInterface implements Runnable{
public void run(){
system.out.println("Hi")
}
}
public class Main{
public static void main()
{
ApnaThreadUsingClass t1 = new ApnaThreadUsingClass();
ApnaThreadUsingInterface a1 = new ApnaThreadUsingInterface();
Thread t2 = new Thread(a1);
}}
- When a Java program starts, the main thread starts running immidiately, responsible for executing the main method of a program