What is Java Runnable and how does it work in simple terms?
I’m an AP programming student in high school, and my assignment is to research or ask others about what “runnable” means in Java. We’re just starting with Object-Oriented Programming (OOP), and we haven’t learned about threads yet. Can someone explain Java Runnable in an easy-to-understand way?
Since you’re just starting with Object-Oriented Programming (OOP) and haven’t touched threads yet, let me break it down in a simple way. Think of java runnable
as a task that a thread can execute. It’s like writing a to-do list and handing it to someone (a thread) to get it done. Instead of writing everything inside the thread itself, Runnable
allows you to define the task separately.
Here’s a very basic example:
class MyTask implements Runnable {
public void run() {
System.out.println("Hello from a separate thread!");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask()); // Create a thread and pass the task
thread.start(); // Start the thread
}
}
Here, MyTask
implements Runnable
, which means we can pass it to a Thread
to run it separately.
Exactly! And just like Sam mentioned, java runnable
helps you run tasks separately. But it also opens the door for multitasking! Imagine you’re cooking AND watching TV at the same time. Normally, a Java program runs one task at a time (sequentially), but with Runnable
, you can run multiple tasks at once (parallel execution).
Here’s a shorter way to do it using a lambda expression (a cool feature in Java):
public class LambdaRunnable {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Running in a thread!");
Thread thread = new Thread(task);
thread.start();
}
}
Instead of creating a separate class like in the previous example, we used a lambda expression to define the run()
method in one line!
Great points! Another advantage of java runnable
is that it allows you to run tasks in a thread even when you don’t need to extend Thread
. In Java, you can only extend one class (no multiple inheritance). So, sometimes, you may already have a class that extends another class but still want it to run in a separate thread. That’s where java runnable
really shines!
For example:
class MyClass {
void display() {
System.out.println("This is MyClass");
}
}
class MyTask extends MyClass implements Runnable {
public void run() {
System.out.println("Running task in a thread");
}
}
public class RunnableExample {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
Here, MyTask
extends MyClass
and implements Runnable
at the same time. If we had extended Thread
instead, we couldn’t extend MyClass
!