Threads in Java: Great Insights

What are Threads in Java ?

Threads in Java are lightweight units of execution within a program that can run concurrently. They allow for concurrent and parallel execution of multiple tasks within a single program. Each thread represents an independent flow of control, enabling the program to perform multiple operations simultaneously.

Different Ways of Creating Threads in Java

There are two ways for creating threads in Java.

Extend the Thread class:

Create a class that extends the Thread class, override the run() method, and call start() to start the thread.

public class MyThread extends Thread {
    
    @Override
    public void run() {
        // Code to be executed by the thread
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        // Create an instance of the custom thread
        MyThread myThread = new MyThread();

        // Start the thread
        myThread.start();
    }
}

Implement the Runnable interface:

Implement the Runnable interface, define the run() method, create a Thread object, and pass the Runnable instance to its constructor.

public class MyRunnable implements Runnable {
    
    @Override
    public void run() {
        // Code to be executed by the thread
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        // Create an instance of the custom Runnable implementation
        MyRunnable myRunnable = new MyRunnable();

        // Create a Thread object and pass the Runnable instance
        Thread thread = new Thread(myRunnable);

        // Start the thread
        thread.start();
    }
}

Please visit implements Runnable vs extends Thread for comprehensive guide.

Thread Priority

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.

The default thread priority in Java is 5. When a new thread is created, it inherits the priority of the thread that created it.

Since the main thread is the entry point for Java programs, any threads created by the main thread will also have a default priority of 5 unless explicitly set to a different value.

Types of Threads in Java

In Java, there are primarily two types of threads in Java: user threads and daemon threads. Let’s explore each type:

1. User Threads:

User threads are the regular threads that are created and managed by the application programmer. These threads are responsible for performing various tasks within the application and are under the programmer’s control.

What is Main Thread?

When the JVM starts, it creates a thread called “Main”. This thread invokes the static main method to start the application.Other threads can be spawned from this main thread.

2. Daemon Threads:

Daemon threads are background threads that provide support to user threads. Their primary purpose is to perform tasks that assist in the maintenance and operation of the application. Unlike user threads, daemon threads do not prevent the JVM from exiting when the main application finishes execution. If all user threads have completed their tasks, and only daemon threads are left, the JVM will exit.

Life Cycle of a Thread

The life cycle of a thread in Java typically consists of several distinct stages:

Threads in Java

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable(Ready to Run)

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. A thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the scheduler.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.A thread can enter in this state because of waiting the resources that are hold by another thread.

A thread becomes “Not Runnable” when one of these events occurs:

  • If sleep method is invoked.
  • The thread calls the wait method and now is waiting for notification.
  • The thread is blocked for I/O.
  • The thread is notified and is blocked for object lock acquisition.
  • The thread is blocked for join completion.It waits for the other thread to finish execution.

5) Terminated

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

Methods in Thread Class

MethodDescription
start()Starts the execution of the thread
run()Contains the code to be executed by the thread
sleep(long milliseconds)Suspends the execution of the thread for the specified time
join()Waits for the thread to finish its execution
isAlive()Checks if the thread is currently running
getName()Retrieves the name of the thread
setName(String name)Sets the name of the thread
interrupt()Interrupts the execution of the thread
isInterrupted()Checks if the thread has been interrupted
setPriority(int priority)Sets the priority of the thread

For More details, please read Methods in Thread Class.

Thread Coordination

The wait(), notify() and notifyAll() methods provide a powerful mechanism for coordinating the execution of multiple threads in Java. By using these methods in conjunction with shared objects, developers can achieve synchronization and communication between threads effectively.

More more in-depth details please read wait, notify and notifyAll

Conclusion: Threads in Java

In summary, threads in Java offer various ways to create and manage concurrent execution. We explored different methods to create threads in Java, such as extending the Thread class and implementing the Runnable interface.

Thread priority assigns importance to threads. User threads are the regular threads that are created and managed by the application programmer. The main thread is the entry point for Java programs. Daemon threads run in the background and don’t prevent program exit.

Knowing the thread life cycle helps control execution and perform operations at different stages. The Thread class manages threads, coordinates their execution, and interacts with them.

By coordinating threads through synchronization, wait(), and notify(), we can achieve proper synchronization and communication.

Leave a Reply

Your email address will not be published. Required fields are marked *