Two Laptop Bag*
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
Author

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

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?

------------------
WebNelly.com
Java/XML Web Development
Check it out!
http://www.webnelly.com


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
Sheriff

Joined: Jul 22, 2000
Posts: 9043
    
  10

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


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
Consider Paul's rocket mass heater.
 
subject: What Is This Program Doing?
 
Similar Threads
IllegalThreadStateException
Regarding Threads
why output is 1 2 only?
Threads: synchronizing a block of code (K&B 1.5)
Thread questions