Runnable
- Java course
- Advanced
- Lesson 56/82
- 5 min
Learn to define tasks with Runnable.
Runnable
Runnable is the interface that represents a thread task. Instead of extending Thread, you implement Runnable; this gives flexibility for classes that already extend another class.
class PrintTask implements Runnable {
public void run() {
System.out.println("Running");
}
}
Thread t = new Thread(new PrintTask());
t.start();Since Java 8 a lambda is shorter: new Thread(() -> System.out.println("Hi")). This is the preferred functional style. Runnable returns no result; use Callable for a result.
Runnable with lambda
Since Java 8 a Runnable can be written as a lambda. With a single abstract method (run), the compiler maps it automatically.
Runnable r = () -> System.out.println("Hi");
new Thread(r).start();This is much shorter than writing an anonymous class. The @FunctionalInterface annotation marks the interface as having a single abstract method; this makes lambda use safe. Modern Java code prefers lambdas.
Practice Implement Runnable with PrintTask
Define a PrintTask class that implements the Runnable interface; in public void run() call System.out.println("Task running"). In a RunnableDemo class write main; create an instance of PrintTask and call run() directly.
Starter code
// Define PrintTask implementing Runnable
// Call println in run()
// Write main in RunnableDemo and call run()Sample solution
class PrintTask implements Runnable {
public void run() {
System.out.println("Task running");
}
}
class RunnableDemo {
public static void main(String[] args) {
new PrintTask().run();
}
}Expected output
Task running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Runnable implementation
class PrintTask implements ____ {
public void run() {
System.out.println("Çalışıyor");
}
}
class PrintTask implements Runnable {
public void run() {
System.out.println("Çalışıyor");
}
}
Explanation: The Runnable interface provides the run() method.
2 What is the name of Runnable's single abstract method?
- call()
- apply()
- get()
- run() Correct answer
Explanation: Runnable's single method is run().
3 Match the task interfaces
| Term | Meaning |
|---|---|
Runnable |
Returns no result |
Callable |
Returns a result |
Thread |
Represents a thread |
@FunctionalInterface |
Marks a single abstract method |