multithreading in java
Multithreading in Java
Multithreading in java is a technique of executing a number of threads concurrently.
Thread is mainly a light-weight sub-process, a smallest unit of processing. Multiprocessing and multithreading, each are used to attain multitasking.
However we use multithreading than multiprocessing as a result of threads share a typical memory space. They do not allocate separate memory space so saves memory, and context-switching between the threads takes less time than process.
Java Multi threading is usually utilized in video games, animation and many others.
By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
Advantages of Java Multithreading
1) It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn’t affect other threads if exception occur in a single thread.
Multitasking is a process of executing a number of tasks concurrently. We use multitasking to make the most of the CPU. Multitasking will be achieved by two methods:
- Process-based Multitasking(Multiprocessing)
- Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
- Each process have its own address in memory i.e. each process allocates separate memory area.
- Process is heavyweight.
- Cost of communication between the process is high.
- Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
- Threads share the same address space.
- Thread is lightweight.
- Cost of communication between the thread is low.
Note: At least one process is required for each thread.
What is Thread in java
A thread is a light-weight sub process, a smallest unit of processing. It’s a separate path of execution.
Threads are impartial, if there happens exception in a single thread, it does not have an effect on different threads. It shares a typical memory space.
As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.