java tutorial - Multithreading in Java - java programming - learn java - java basics - java for beginners
- Multithreading is nothing but the process of executing multiple threads simultaneously.
- The Thread is fundamentally a lightweight sub-process, which is known as smallest unit of processing. Multiprocessing as well as multithreading are used to achieve multitasking.
- But we use multithreading than multiprocessing since threads share a common memory area. Here, they do not allocate separate memory area so it saves memory, and then context-switching between the threads takes fewer times than process.
- Multithreading is generally used in games, animation etc.
Learn Java - Java tutorial - Multithreading in Java - Java examples - Java programs
Advantages of Java Multithreading
- It doesn't block the user as threads are independent and you can perform multiple operations at same time.
- In multithreading, we can achieve several operations together so it will save time.
- The Threads are independent hence it doesn't affect other threads if exception occurs in a single thread.
- It is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
- Process-based Multitasking(Multiprocessing)
- Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)
- Each process has its own address in memory i.e. each process allocates separate memory area.
- Process is heavyweight.
- Cost of communication between the processes is high.
- Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
Thread-based Multitasking (Multithreading)
- Threads share the same address space.
- Thread is lightweight.
- Cost of communication between the thread is low.
What is Thread in java ?
- Thread is a lightweight sub process, a smallest unit of processing. It have a separate path of execution.
- They are independent, if there occurs any exception in one thread, it doesn't affect other threads. It shares a common memory area.
- Thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and a single process can have multiple threads.