Multiprocessing:
Multiprocessing represents a type of multitasking which is based upon processes. Context switching in Multiprocessing, is done in-between processes. For example: Listening music, downloading file, Typing in notepad etc from internet at the same time. You can clearly identify that all applications like music software, notepad etc are independent. Multiprocessing is handled at OS level.
Process:
A process has a it’s own execution environment i.e. separate memory area will be allocated to each process. Context switch time between processes is more because switching will be done between different memory areas.
Multithreading:
Multithreading represents a type of multitasking which is based upon threads. Context switching in Multithreading, is done in-between threads. In multithreading, multiple independent tasks will execute simultaneously and these tasks will be the part of same program or application. Multithreading is handled at application or program level.
Thread:
A thread refers to a lightweight process. A thread will use the process’s memory area or execution environment. Context switch time between threads is less because switch is done within the same process’s execution environment or memory area.
A thread can be consider as a flow of execution representation. Every thread has a task or job associated with it.
Note: A thread cannot be exist without a process, it exist with-in the process.
Difference between process and thread in java:
Process | Thread |
|
|
Thread Example
class Test extends Thread{ public void run( ){ for(int i = 3; i > 0; i--){ System.out.println("Test class thread is running: " +i); } } } public class Main extends Thread{ public void run( ){ for(int i = 3; i > 0; i--){ System.out.println("Main class thread is running: " +i); } } public static void main(String args[ ]){ Test test = new Test(); Main main = new Main(); test.start(); main.start(); } } |
Output
Test class thread is running: 3 Test class thread is running: 2 Test class thread is running: 1 Main class thread is running: 3 Main class thread is running: 2 Main class thread is running: 1 |
Java interview questions on multithreading
- What is multithreading?
- Difference between process and thread in java?
- What is thread in java?
- What is the difference between preemptive scheduling and time slicing?
- What is join method in java?
- What is the difference between sleep and yield method?
- Is it possible to start a thread twice in java?
- Can we call run method directly in java?
- What is daemon threads in java?
- Can we make the user thread as daemon thread if thread is started?
- What is synchronization?
- What is synchronized block in java?
- What is synchronized method in java?
- What is static synchronization in java?
- What is deadlock in java?
- What is starvation in java?