Описание тега runnable
A question about Runnable
almost always really is a question about Java threads: A Java program can not create any useful thread without providing a run()
method for some new Runnable
instance*. That was the original reason for the Runnable
interface to exist, and multi-threading may still be the most common reason why Runnable
instances are created.
Some beginner programmers attempt to learn about multi-threading before they have a firm understanding of what an interface is or, the difference between a variable and an instance, etc. They may ascribe special properties to the run()
method when the real magic happens in a Thread
object's start()
method. This is apparent in questions (and, in answers) about, "what happens when you call the run()
method?" An experienced Java programmer knows that run()
is just like any other method: If you want to know what it does, you should ask the person who wrote it.
The Runnable
interface also is used to define tasks that may be executed by a java.util.concurrent.ExecutorService
(usually, a thread pool) and, like any other interface, it may be used for in-thread callbacks, or in any other way that a programmer sees fit.
The Runnable
interface, just like any other interface, may be used by creating a named class that implements
it:
class Foobar implements Runnable {
public Foobar(...) { ... }
@Override
public void run() { doSomething(); }
}
Runnable r = new Foobar(...);
And, like any other interface or class, it may be used as the template for an anonymous inner class:
Runnable r = new Runnable() {
public void run() { doSomething(); }
};
Finally, since Java8, Runnable
is an @FunctionalInterface
which means that a new instance also can be created with a lambda expression:
Runnable r = () -> doSomething();
Answers to questions about run()
should emphasize that t.start()
is the method that the library provides for your code to call when it's time to start a new thread, and run()
is the method that you provide for the library to call in the new thread.
See Defining and Starting a Thread tutorial for simple examples of Runnable
implementations.
*A Thread
instance is a Runnable
instance.