Runnable Object

suggest change

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 Java 8:

public static void main(String[] args) {
    Runnable r = () -> System.out.println("Hello world");
    new Thread(r).start();
}

Runnable vs Thread subclass

A Runnable is more general, because the class that implements Runnable can extend 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents