Creating a thread in Java is quite easy. In this post, we will learn how to create a thread in Java with an example. There are two ways to create a thread in Java:
- By extending a Thread class and
- By implementing the Runnable interface
Extending the Thread class
To create a thread by extending the 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:
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 a thread that will print the message:
Thread is running by extending Thread class...
Implementing the Runnable interface
The other way to create a thread in Java is by implementing the Runnable
interface. The Runnable
interface has a single method called run()
that needs to be implemented. Following is an example:
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 have created a thread, 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()
: Thesleep()
method causes the current thread to pause execution for a specified number of milliseconds.join()
: Thejoin()
method causes the current thread to wait until the thread on which it is called has completed execution.yield()
: Theyield()
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.