0% completed
The Runnable
interface is a core component of Java's multithreading framework. It represents a task that can be executed by a thread and defines a single method, run()
, which contains the code that should execute concurrently. Unlike extending the Thread
class, implementing Runnable
allows a class to define a task while still extending another class if needed. This approach promotes better separation of concerns and makes your code more flexible and reusable.
Thread
class restricts you from extending any other class since Java supports single inheritance.Runnable
allows your class to extend another class while still enabling multithreading.run()
) is separated from the thread control mechanism. This makes the code more modular and easier to maintain.Thread
constructor, enabling you to use different thread implementations without changing your task code.// Implementing the Runnable interface: public class MyTask implements Runnable { @Override public void run() { // Code to be executed in the new thread } } // Executing a new thread: Thread thread = new Thread(new MyTask()); thread.start();
MyTask
) implements Runnable
and overrides the run()
method with the desired task.Thread
object is created by passing an instance of MyTask
to its constructor.start()
on the thread initiates the new thread, which in turn invokes the run()
method.In this example, we define a class Task
that implements Runnable
. The run()
method prints a simple message multiple times with a short pause using Thread.sleep()
. We then create a thread with this task and start it.
Example Explanation:
Runnable
and overrides run()
to print a count from 1 to 5.Thread.sleep(1000)
to pause for 1 second between iterations.Thread
is created with an instance of Task
.start()
initiates the thread, causing the run()
method to execute concurrently with the main thread.The Runnable
interface is a flexible way to define tasks that can be executed by threads without being limited by Java's single inheritance restriction. By implementing Runnable
, you separate the task's logic from thread management, allowing greater modularity and reuse.
.....
.....
.....