Creating Threads by Implementing Runnable Interface
Table of Contents
- Introduction
- Creating a Thread by Implementing the Runnable Interface
- Code Explanation and Output
- Conclusion
1. Introduction
Multithreading is a fundamental concept in Java that allows a program to perform multiple tasks simultaneously, making it efficient and responsive. One of the key ways to achieve multithreading in Java is by using the Runnable
interface. This approach offers a flexible way to manage threads without extending the Thread
class, thus allowing the class to extend other classes as well.
In this article, we will focus on how to create and manage threads by implementing the Runnable
interface. The provided Java project demonstrates a basic implementation of multithreading in which two threads execute tasks in parallel, simulating real-world scenarios like server requests or background computations.
2. Creating a Thread by Implementing the Runnable Interface
Why Use Runnable
Interface?
The Runnable
interface in Java is often preferred over extending the Thread
class because it allows more flexibility. Since Java allows single inheritance, a class that implements Runnable
can still extend another class, whereas a class that extends Thread
cannot.
Comparison Between Extending Thread
vs Implementing Runnable
Aspect | Extending Thread Class |
Implementing Runnable Interface |
---|---|---|
Flexibility | Cannot extend another class | Can extend another class |
Code reusability | Lesser reusability | Greater reusability |
Preferred in simple applications | Yes | No |
Preferred in complex applications | No | Yes |
When to Use Runnable
?
- When you need to extend another class and still implement multithreading.
- When you want a clean separation of the task (logic) from the thread management.
3. Code Explanation and Output
Complete Code Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.studyeasy; import java.util.Random; import static java.lang.Thread.sleep; class MyCounter implements Runnable { private int threadNo; public MyCounter(int threadNo) { this.threadNo = threadNo; } @Override public void run() { for (int i = 0; i < 10; i++) { try { Random random = new Random(); sleep(random.nextInt(1000)); // Thread pauses for a random time } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread no: " + threadNo + " and iteration no: " + i); } } } public class Main { public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new MyCounter(1)); // Creating thread 1 Thread thread2 = new Thread(new MyCounter(2)); // Creating thread 2 thread1.start(); // Starting thread 1 thread2.start(); // Starting thread 2 } |
Code Breakdown
- MyCounter Class:
- Implements the
Runnable
interface. - Contains a constructor that accepts an integer
threadNo
representing the thread number. - In the
run
method, afor
loop runs 10 iterations, with each iteration pausing for a random amount of time (between 0-1000 milliseconds) before printing the current thread number and iteration.
- Implements the
- Main Class:
- The
main
method creates two threads, each executing an instance of theMyCounter
class. - The
start()
method begins the execution of both threads in parallel.
- The
Output Example
1 2 3 4 5 6 |
Thread no: 1 and iteration no: 0 Thread no: 2 and iteration no: 0 Thread no: 2 and iteration no: 1 Thread no: 1 and iteration no: 1 Thread no: 1 and iteration no: 2 Thread no: 2 and iteration no: 2 |
Key Concepts
- Multithreading: Running multiple threads in parallel for concurrent task execution.
- Runnable Interface: Allows defining the task for the thread separately from the thread management.
- Thread Synchronization: Though not explicitly covered in this example, synchronization becomes important when threads share resources.
4. Conclusion
In this article, we explored the creation of threads by implementing the Runnable
interface in Java. This approach provides flexibility, especially when a class needs to extend another class while still implementing multithreading. Understanding how to efficiently use threads is crucial for building responsive and efficient Java applications.
By using the Runnable
interface, you can separate the thread logic from the actual thread management, making the code cleaner and more maintainable. Whether you are developing background services, parallel computations, or other concurrent tasks, this method is an essential tool in a Java developer’s skillset.