2

Well, the title says it all: What will happen if you would use return in the run() method implemented from Runnable? Will it make the Thread die, or not?

cvbattum
  • 811
  • 2
  • 15
  • 32

5 Answers5

5

Yes, but you can't return any value, because run is a void type.

Example

Using Return to end the thread

public void run()
{
     while(true)
     {
          return;
          // This is fine, and will stop the thread.
     }
}
christopher
  • 26,815
  • 5
  • 55
  • 89
3

Yes.

When you return from the run() method the thread dies - but the object persists until it becomes unreachable.

See this article about the lifecycle of threads.

Also see this related question.

Community
  • 1
  • 1
selig
  • 4,834
  • 1
  • 20
  • 37
2

If you put a return statement in your runnable the thread dies, and nothing more will happen.

If you need to do something like return a value after thread completion, have a look at Callable

It can return a future object that is returned when a thread is finished.

bpoiss
  • 13,673
  • 3
  • 35
  • 49
  • The poster is asking about if the thread terminates. Also be careful of the word "exit" since `System.exit(...)` is obviously a different beast. – Gray May 31 '13 at 17:24
2

It depends.

If you created and started a Thread with that Runnable, then the return statement will lead to the termination of the thread. It doesn't cause immediate termination of the thread. For example, any enclosing finally blocks are still executed.

new Thread( myRunnable ).start()

However, there are other cases where a return statement in a Runnable does not cause termination of the current thread.

For example, you can also call a Runnable directly. Fortunately, the return from the run() method does not kill the thread of the caller.

myRunnable.run();

And you can put a Runnable into a ThreadPoolExecutor, which may run multiple Runnables on a single thread. Return statements in these Runnables do not cause termination of the re-used thread.

executorService.submit( myRunnable );
executorService.submit( myOtherRunnable );
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • The return does make the thread die in the `Thread` context. Obviously there is other code that is run internal to `Thread` but in terms of the question scope saying that it doesn't is misleading. The difference between overriding `Thread.run()` and the `if (target!=null) target.run()` method is very subtle. – Gray May 31 '13 at 17:27
  • @Gray - Clarified first paragraph. Also, consider a return enclosed in a try/finally. After the return statement, the thread continues to execute the finally block, regardless. – Andy Thomas May 31 '13 at 17:49
  • Not sure why someone downvoted this after the edit above. – Andy Thomas May 31 '13 at 19:30
1

It will stop execution and if theres no other references to the Thread object it will eventually be garbage collected.

koljaTM
  • 10,064
  • 2
  • 40
  • 42