Java Multi-threading

Multithreading concept

Thread is basically a sub-process. The smallest processing unit of a computer that can perform a single job. In Java, threads are managed by the Java virtual machine (JVM).

Multi-thread is a process that executes multiple threads simultaneously. A Java application in addition to the main thread can have other threads executing concurrently, making the application run faster and more efficiently.

For example: Web browsers or music players are a typical example of multithreading.

Advantages of multithreading


It doesn't block users because the threads are independent and you can do multiple jobs at the same time.
Each thread can pool and share resources during runtime, but can execute independently.
Threads are independent so it does not affect other threads if an exception occurs in a single thread.
Multiple activities can be done together to save time. For example, an application can be split into: the main thread that runs the user interface and the slave threads that send processing results to the main thread.

Disadvantages of multithreading


The more threads, the more complex the processing.
Handling problems with memory contention and data synchronization is quite complicated.
It is necessary to detect and avoid dead locks, threads that run without doing anything in the application.

Thread Life Cycle

Thread lifecycle in Java is controlled by JVM. Java defines thread states in static properties of the Thread.State class:

NEW : This is the state when the thread has just been initialized by the constructor of the Thread class but has not been started() yet. In this state, the thread is created but has not been allocated resources nor is it running. If the thread is in this state and we call the forced methods stop, resume, suspend... it will cause an IllegalThreadStateException exception to occur.


RUNNABLE : After calling the start() method, the test thread has been allocated resources and the CPU dispatch schedules for the test thread also begin to take effect. Here, we use the state Runnable, not Running, because the thread is not actually always running, but depending on the system, there is different CPU coordination.


WAITING: Thread waits indefinitely until another thread wakes it up.


TIMED_WAITING: Thread waits for a certain time, or another thread wakes it up.


BLOCKED: This is a form of “Not Runnable” state, a state when the Thread is still alive, but is not currently selected to run. Thread waits for a monitor to unlock an object it needs.


TERMINATED : A thread is in terminated or dead state when its run() method exits.

Thank for reading the post.