Functional Interfaces: Runnable

Unit of processing that can be assigned to a thread for execution.

Overview

Example

Create a Runnable and invoke its run method on different threads:

Runnable identify = () -> 
    System.out.printf("%d: %s%n", System.currentTimeMillis(), Thread.currentThread().getName());
new Thread(identify).start(); // Run identify on a new thread.
identify.run();               // Run identify on this (main) thread.

In this example, a reference to a lambda implementation of Runnable is declared and initialized as the local variable identify. A Thread is created, passing this lambda as a constructor parameter; then, start() is invoked on the new thread, to start execution of identity on a separate thread. Then identify.run() is invoked on the main thread.

The output from the above will be slightly different every time, but it will generally look something like

1612592939700: main
1612592939706: Thread-6

Since both threads (main and—in the example output above—Thread-6) are writing to a shared resource (the standard output device accessed via System.out), it’s actually possible to get interleaved output between the 2 threads.