Create Thread in Java

Creating a thread in Java is quite easy. In this post, we will learn how to create thread in Java with an example.

There are two ways to create a thread in Java:

  • By extending Thread class and
  • By implementing Runnable interface

Extending Thread class

To create thread in Java by extending Thread class, we need to override the run() method. The run() method is the entry point for the thread and contains the code that will be executed by the thread.

Following is an example to create thread extending Thread class:

class MyThread extends Thread {

    public void run() {
        System.out.println("Thread is running by extending Thread class...");
    }

    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();
    }
}

This code will create thread that will print the message:

Thread is running by extending Thread class...

Implementing Runnable interface

The other way to create thread in Java is by implementing Runnable interface. The Runnable interface has a single method called run() that needs to be implemented.

Following is an example to create thread implementing Runnable interface:

class MyRunnable implements Runnable {

    public void run() {
        System.out.println("Thread is running by implementing Runnable interface...");
    }

    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}

The output of the above program will be:

Thread is running by implementing Runnable interface...

Once we create thread in Java, we can start it by calling the start() method. The start() method will cause the thread’s run() method to be executed by the Java runtime.

There are several methods available in the Thread class that we can use to control the behavior of a thread. Some of the commonly used methods are:

  • sleep(): The sleep() method causes the current thread to pause execution for a specified number of milliseconds.
  • join(): The join() method causes the current thread to wait until the thread on which it is called has completed execution.
  • yield(): The yield() method causes the current thread to pause execution and allow other threads to execute.

Threads can also be given priority using the setPriority() method. Threads with higher priority will be given more CPU time compared to threads with lower priority.

Create a thread with executor service

Threads can also be created and managed using executor services. Executor services are a part of the java.util.concurrent package and provide a way to create and manage a pool of threads. This can be useful for improving the performance and scalability of a program that makes use of multiple threads. Here is an example of creating and starting a new thread using an executor service:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample implements Runnable{

	@Override
	public void run() {
		System.out.println("Running inside thread "+Thread.currentThread().getName());
		
	}

	public static void main(String[] args) {
		// create an executor service with a fixed thread pool
		ExecutorService executor = Executors.newFixedThreadPool(4);

		// submit a new runnable task for execution
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
		executor.submit(new ExecutorServiceExample());
	}
}

Let’s see the output of the above code execution:

Running inside thread pool-1-thread-2
Running inside thread pool-1-thread-1
Running inside thread pool-1-thread-4
Running inside thread pool-1-thread-3
Running inside thread pool-1-thread-3
Running inside thread pool-1-thread-4
Running inside thread pool-1-thread-3
Running inside thread pool-1-thread-4

We can see in the above output that, even though we’ve submitted many instances of the Runnable thread, it is executing only the 4 number of threads. Because, while instantiating ExecuterService we’ve defined the max number of threads is 4.

Conclusion

Threads are a useful and powerful feature of the Java language that allows us to create concurrent programs. Whether we extend the Thread class or implement the Runnable interface, creating and using threads in Java is straightforward and can greatly improve the performance of our programs.

FAQs

What is the difference between extending Thread and implementing Runnable for creating threads?

Extending the Thread class limits your ability to extend other classes, while implementing Runnable allows for better flexibility by separating the thread’s behavior from the class it’s in.

Can I control the execution sequence of threads in Java?

Yes, you can control thread execution using methods like join(), yield(), and synchronization mechanisms like synchronized blocks to coordinate thread activities.

What is the difference between start() and run() methods in Java threads?

The start() method is used to begin the execution of a thread, while the run() method defines the code to be executed in the new thread. You should not call run() directly; instead, use start() to initiate the thread.

Is it possible to set the priority of a Java thread?

Yes, you can set the priority of a thread using the setPriority() method. However, the actual priority is dependent on the operating system and may not be guaranteed.

How can I safely terminate a thread in Java?

You can gracefully terminate a thread by using flags or conditions within the run() method, or by using methods like interrupt() to stop the execution of a thread safely.