jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes What Is This Program Doing? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Is This Program Doing?" Watch "What Is This Program Doing?" New topic

What Is This Program Doing?

Gary Farms
Ranch Hand

Joined: Jun 24, 2000
Posts: 57
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

Joined: May 08, 2001
Posts: 1932
Wow, completely passed over the run() vs. start() call, good catch there you two! Makes sense now why it doesn't work.
*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

Joined: Nov 04, 2001
Posts: 35
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?

Java/XML Web Development
Check it out!

WebNelly.com<br />Java/XML Web Development<br />Check it out!<br /><a href="http://www.webnelly.com" target="_blank" rel="nofollow">http://www.webnelly.com</a>
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059

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).]

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I agree. Here's the link: http://aspose.com/file-tools
subject: What Is This Program Doing?
It's not a secret anymore!