All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Creating Threads In Java

Last Updated : Mar 11, 2024

Creating Threads In Java

In this article we will show you the solution of creating threads in java, Java's ability to create threads enables concurrent task execution, which improves the speed and responsiveness of programs.

Java has a wide range of capabilities for managing and creating threads. The Runnable interface and the Thread class serve as basic building elements.

A thread can be launched using the start() method after it has been created, which asynchronously calls the run() method. Multiple tasks can be completed simultaneously by threads running concurrently.

To prevent race circumstances and guarantee thread safety, however, appropriate synchronization techniques must be used.

Java's thread generation feature enables programmers to make use of parallelism and unleashes the potential for productive and scalable systems.

We'll talk about the Java concept of creating threads now.

Step By Step Guide On Creating Threads In Java :-

import java.lang.Thread;
public class ThreadExample extends Thread {
    private String threadName;
    public ThreadExample(String name) {
        this.threadName = name;
    }
    public void run() {
        System.out.println("Thread " + threadName + " is running.");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("Thread " + threadName + " interrupted.");
        }
        System.out.println("Thread " + threadName + " finished.");
    }
    public static void main(String[] args) {
        System.out.println("Main thread started.");
        ThreadExample thread1 = new ThreadExample("Thread 1");
        ThreadExample thread2 = new ThreadExample("Thread 2");
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        System.out.println("Main thread finished.");
    }
}
  1. As you can see, we write the Java code required to create threads here.
  2. Importing the Thread class from java.lang package is the first action we do.
  3. Creating ThreadExample, a variant of the Thread class, is performed. This indicates that our ThreadExample class inherits traits from Thread.
  4. We declare a private instance variable named threadName inside of ThreadExample, and it will store the thread's name.
  5. The ThreadExample class is given a constructor that accepts a name-based String parameter. When we create an instance of ThreadExample, we can use this constructor to give the thread a name.
  6. The run() method that was inherited from Thread is overridden. As soon as the thread starts, this method will execute the code.
  7. Using the threadName variable, we print a message stating that the thread is active right now.
  8. Using Thread.sleep(2000), we halt the thread for 2000 milliseconds (2 seconds) to simulate some work.
  9. While the thread is dozing, we catch any InterruptedException that might occur, and we print a message notifying the user that the thread was interrupted.
  10. We output a message stating that the thread has completed running.
  11. We define the main() function, which is where our Java programme starts.
  12. We print a message letting everyone know the main thread has begun.
  13. By giving "Thread 1" and "Thread 2" to their respective constructors, we create two instances of the ThreadExample class, referred to as thread1 and thread2, respectively. This develops two distinct threads.
  14. By using the start() method on each thread object, we begin the threads' execution. Internally, this method makes an asynchronous call to the run() method, enabling concurrent operation of the threads.
  15. We wait for threads 1 and 2 to complete their execution using the join() method before moving on to the main thread. By doing this, it is made sure that the main thread won't end before the other threads have finished.
  16. While we wait for the threads to connect, we detect any InterruptedException that might happen and print a message indicating that the main thread was interrupted.
  17. In order to signal that the main thread's execution is complete, we print a message at the end.

Conclusion :-

As a result, we were able to understand the Java notion of creating threads.

We also discovered that we could set unique behavior for each thread by extending the Thread class and overriding the run() method.

The code displays how to make two instances of the ThreadExample class, which correspond to two distinct threads.

The start() method, which internally calls the run() method asynchronously, is used to start these threads.

Using the join() method, the main thread waits until all other threads have finished running their code in order to make sure that no threads are still running while the main thread is still waiting for them to do so.

The code then publishes messages outlining each thread's progress and the end of the main thread.

I hope this article on creating threads in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪