When would you call java's thread.run() instead of thread.start()?

When would you call Java's thread.run() instead of thread.start()?


Solution 1:

You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.

Solution 2:

Never. Calling run() directly just executes the code synchronously (in the same thread), just like a normal method call.

Solution 3:

Taken form the Code Style Java threads FAQ:

Q: What's the difference between a thread's start() and run() methods?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.