Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and run()

 
Tom Scott
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

My understanding was that if I invoke run()from a thread object directly this would be legal but not create a new call stack or a new thread.

So I wrote the following:


And invoked run() as below....



But I got output:

run:
Invocation : 0: current thread = Thread[Thread-0,5,main]
Invocation : 1: current thread = Thread[Thread-1,5,main]
END
BUILD SUCCESSFUL (total time: 0 seconds)


If I take away the for loop delay statement, I can see the third display from the direct run() call in the main thread. If I put the delay in then I only get two lines as above. I expected to see all three displays as below (in maybe a different order) even with the delay.

run:
Invocation : 0: current thread = Thread[main,5,main]
END
Invocation : 1: current thread = Thread[Thread-0,5,main]
Invocation : 2: current thread = Thread[Thread-1,5,main]
BUILD SUCCESSFUL (total time: 0 seconds)

Can anyone explain why this didn't happen?
Thanks.
-Tom
 
Henry Wong
author
Marshal
Pie
Posts: 21003
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I take away the for loop delay statement, I can see the third display from the direct run() call in the main thread. If I put the delay in then I only get two lines as above. I expected to see all three displays as below (in maybe a different order) even with the delay.


If you invoke the run() method directly, the thread object will "not create a new call stack or a new thread". However, keep in mind that you did not override the thread object's run() method. The thread object's run() method is not necessaryly your runnable's run() method.

The thread object's run() method which will check the state of the thread, and call runnable's run() method. By putting in the delay, you are making sure that the thread is no longer in a runnable state, and hence, will not call your run() method.

If you want to call the run() method, use "r.run()" -- don't play with the thread's internal methods.

Henry
 
Tom Scott
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fast answer - thanks!

run() method, use "r.run()" -- don't play with the thread's internal methods.


Rest assured I'd only code this to see what happens - like the time I bent Dad's fishing rod a just a little bit too much to see what a big fish would do...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic