Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What Is This Program Doing?

 
Gary Farms
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following program prints 1 2 3 4 and I don't know how. As soon as i=3, doesn't this call an interrupt? Will the catch get entered? I don't understand the flow of this program.
I even passed object gf to run, and then did a gf.start() to deliberately start a thread and got the exact same output result. How?
Here's the program:

(edited by Cindy to format code)
[This message has been edited by Cindy Glass (edited November 06, 2001).]
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, completely passed over the run() vs. start() call, good catch there you two! Makes sense now why it doesn't work.
Jason
*removed my earlier guesses, no need in getting wrong answers around

[This message has been edited by jason adam (edited November 07, 2001).]
 
Kris Nelson
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every Java book I've read also states that you shouldn't call the run() method of a Runnable object, but instead call the start() method. It may not make a difference in the way this piece of code is running, but we don't want anybody to start any bad habits now, do we?

------------------
WebNelly.com
Java/XML Web Development
Check it out!
http://www.webnelly.com
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you change gf.run() to gf.start(), you will get the output
1 2 3 caught

When you call gf.run(), you are not starting a new thread but merely calling the run method of the MyThread class. That's not the same thing.

When you call interrupt(), you are calling it on the MyThread class (this.interrupt()). That will not affect the main thread which is running the run() method.

Thread.interrupted() is a static method that always works on the current thread - your call merely tests if the main thread is interrupted, which it isn't.

[This message has been edited by Marilyn deQueiroz (edited November 07, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic