The Runnable
interface defines a single method, run()
, meant to contain the code executed in the thread.
The Runnable
object is passed to the Thread
constructor. And Thread's start()
method is called.
Example
public class HelloRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello from a thread");
}
public static void main(String[] args) {
new Thread(new HelloRunnable()).start();
}
}
Example in Java8:
public static void main(String[] args) {
Runnable r = () -> System.out.println("Hello world");
new Thread(r).start();
}
Runnable vs Thread subclass
A Runnable
object employment is more general, because the Runnable
object can subclass a class other than Thread
.
Thread
subclassing is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread
.
A Runnable
object is applicable to the high-level thread management APIs.