Runnable
Unit of processing that can be assigned to a thread for execution.
Primarily intended for use as a unit of processing operations that can be executed in a separate thread from the originator. For example, an instance of a Runnable
implementation may be passed to a new Thread
in the Thread(Runnable)
constructor; when the Thread.start()
method is invoked, the new execution thread is started, and the Runnable
.run()
method is invoked in that thread.
The method to be implemented is declared as void run()
. Thus, an implementing lambda must take no parameters, return no value, and throw no checked exceptions.
While Runnable
is intended for use as a basic “atom” of concurrent processing, it is not required to be used in a concurrent mode. In particular, unlike Thread.start()
, Runnable
.run()
may be invoked multiple times, from any thread.
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.