...
Invoking the Thread.start()
method tells the Java runtime to start executing the thread's run()
method using the started thread. Invoking a Thread
object's run()
method directly is incorrect. When a a Thread
object's run()
method is invoked directly, the statements in the run()
method are executed by the current thread, rather than by the newly created thread. Furthermore, if the Thread
object was constructed by instantiating a subclass of Thread
that fails to override the run()
method rather than being constructed from a Runnable
object, calls to the subclass's run()
method invoke Thread.run()
, which does nothing.
...
Code Block | ||
---|---|---|
| ||
public final class Foo implements Runnable { @Override public void run() { // ... } public static void main(String[] args) { Foo foo = new Foo(); new Thread(foo).start(); } } |
Exceptions
THI00-EX0: The run()
method may be directly invoked when during unit testing functionality. Note that this method cannot be used to test a class for multithreaded use.
...
Code Block | ||
---|---|---|
| ||
public void sampleRunTest(){ Thread thread = new Thread(new Runnable() { @Override public void run() { // ... } }); ((Runnable) thread).run(); // ExceptionTHI00-EX0: ThisDoes does not start a new thread } |
Casting a thread to Runnable
before calling the run()
method documents that the explicit call to Thread.run()
is intentional. Adding an explanatory comment alongside the invocation is highly recommended.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4d99a72ee931051f-a694333f-41a64f08-b84da9a4-776d2892d1c660dae502bedf"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | Interface Runnable and class | ]]></ac:plain-text-body></ac:structured-macro> |
...