Basics of Java Threads:
A thread in Java facilitates the performance of multiple activities inside a single process. It is regarded as a lightweight process. A thread can also be defined as a sequence of executed statements. Every thread in Java has its own stack, program counter and local variables. Java threads may also be a nested series of method calls. The memory, per-process state and files are shared by threads.
Uses of threads in Java:
- To perform background or asynchronous processing
- To enhance the sensitivity of GUI applications
- To implement the positive sides of multiprocessor systems
- To streamline programming logic in the case of the existence of multiple
There exist two execution paths when a thread is called. One of the two paths is used for thread execution and the other one will trail the statement succeeding the thread invocation. Each thread in Java has a separate memory space and stack.
The risk factors encountered while using threads in Java codes are as follows.
- Proper coordination between the threads is required in cases where threads access common variables to view data consistently.
- The performance and maintenance of threads, if overused in the programs, becomes difficult.
Life Cycle of Threads in Java:
At any instant of program execution, the threads in Java exist in any one of the below-mentioned states.
- Timed waiting
A detailed view of Life Cycle of thread in Java
The newly created thread is in the state ‘New’. It is not progressed to run at this state. The execution of the code of a thread in the new state is yet to take place. It is yet to run.
The threads in the runnable state are ready to run. A thread in this state maybe ready to run at any time instant or may already be running. The thread scheduler hones the responsibility of allocating time for the thread to run. Each individual thread is allocated a specific time in a multi-threaded program. Each individual thread runs for a small duration and then encounters a pause. The CPU is then relinquished to another thread to provide a chance for the other threads to run. At this point, all the ready to run threads that are waiting for the CPU and the threads that are running currently lie in a runnable state.
Check out our free technology courses to get an edge over the competition.
Explore our Popular Software Engineering Courses
Waiting /Blocked state:
A thread is in any one of the below-mentioned states when it is temporarily not operating.
A thread waiting for the completion of I/O is in a blocked state. The thread scheduler’s function is to schedule the execution of a blocked or waiting thread by reactivating it. Any thread in this state is not allowed for the further continuation of execution till it is transformed to a runnable state. The threads in the block or waiting state do not use any CPU cycle.
A thread is forced to be blocked when it attempts to access a code’s protected section that is protected by some other thread at present. The scheduler transforms one of the threads waiting for a protected section into a runnable state when the section is unlocked for all the threads. On the other hand, a thread exists in a waiting state while it waits for the other thread on a particular condition. The threads in the waiting state are pushed to a runnable state once the condition specified for waiting is satisfied. If a thread running at present is moved to a waiting / blocked state, the thread scheduler schedules another thread from the runnable sequence to run.
When a method is invoked with a time out argument, the thread exists in a timed waiting state. A thread continues to lie in this state till the completion of specified timeout or until the reception of a notification. For example, a thread is shifted to a timed waiting state if it invokes conditional wait or sleep.
The termination of threads takes place because of any one of the following reasons.
- The Normal exit of the thread on completion of the execution of the code segments within the thread.
- Occurrence of any rare erroneous event such as an unhandled exception and segmentation fault.
A thread in a terminated state does not consume any CPU cycles.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
In-Demand Software Development Skills
Implementation of thread states in Java:
To accomplish the current state of a thread in Java, we use the method Thread.getState(). Java also offers the java.lang.Thread.State class in which the ENUM constants for a thread’s state is defined. The details are summarized in the table below.
|New||public static final Thread.State NEW||It is the thread state of the thread that is just created and yet to start its execution.|
|Runnable||public static final Thread.State RUNNABLE||It describes the state of a thread that is already running or a thread that is in ready to run state.
The same thread can be in a runnable state for the Java Virtual machine and waiting state for other operating system resources such as a processor.
|Blocked||public static final Thread.State BLOCKED||It describes the state of a thread that is blocked waiting for the monitor lock. It remains in the same state until the monitor block enters a synchronized method/block or re-enters the synchronized method after invoking the Object.wait().|
|Waiting||public static final Thread.State WAITING||It describes the state of a thread that is waiting due to the invoking of one of the following methods.
The waiting state may be because of the completion of a particular task by another thread.
|Timed waiting||public static final Thread.State TIMED_WAITING||It is a state of the thread that waits for a specified time. The invocation of any of the following methods results in a timed waiting state of a thread with an assigned positive waiting time.
|Terminated||public static final Thread.State TERMINATED||It is the state of a thread that has completed executing its constituent code statements.|
The thread rests in a NEW state when it is just created. When the .start() method is invoked on a thread, it is moved to a Runnable state by the thread scheduler. When the join() method is invoked on a thread instance, the thread that is executing the code statement currently will wait for this thread to terminate. So, prior to the printing of the final statement on the console, the join() function is invoked on thread 2 by the program and keeps the thread1 on wait till the thread2 completes its execution and moves to the Terminated State. Since thread1 is waiting for the completion of thread2’s execution, it is put in the WAITING state.
Read our Popular Articles related to Software Development
Merits and Limitations of using threads in Java programs:
The use of threads in Java programs has the following benefits.
- Reduction in time taken to develop the code
- Reduced maintenance costs
- Enhanced performance of complex applications
- Boosting the responsivity of the user interfaces
- Parallelizing the tasks
- Threads are used in server applications to improve the high throughput and utilization of resources.
- If all the CPU’s computing resources cannot be used by a thread, the running of another thread will keep these engaged.
- If the same set of data is operated on by several threads, their cache can be shared. This leads to the better usage of cache or harmonization of its values.
There are several drawbacks of using threads in Java programs. Some of them are listed below.
- While sharing caches, translation lookaside buffers (TLBs) or any other hardware resources, multiple threads may interfere with each other.
- Even when only a single thread is operating, the execution time of a thread cannot be enhanced. However, the degradation of the execution time is permitted. This may be due to the additional pipeline stages and/or the slower frequencies that are required for the accommodation of the thread-switching hardware.
- Numerous changes are required in both operating systems and application programs as compared to multiprocessing because hardware support is more exposed to the software in multithreading.
If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.