This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I found the following interesting question on a mock exam: When application A below is run, two threads are created and started. Each thread prints a message just before terminating. Which thread prints its message first? class A { private Thread t1, t2; public static void main(String[] args) { new A(); } A() { t1 = new T1(); t2 = new T2(); t1.start(); t2.start(); } class T1 extends Thread { public void run() { try { sleep(5000); // 5 secs } catch (InterruptedException e) { } System.out.println("t1 done"); } } class T2 extends Thread { public void run() { try { t1.sleep(10000); // 10 secs } catch (InterruptedException e) { } System.out.println("t2 done"); } } } The answer is T1 since even though it looks like T2 will put T1 to sleep for an even longer amount of time, sleep() is a static method and executes on the currently running thread. Cool. My question is, is why is ANYTHING printed out at all? I thought that an InterruptedException was only thrown when a sleeping or waiting thread received an interrupt() call from an executing thread. No such call is coded here. I didn't think that such an exception was automatically thrown when a sleeping or waiting thread entered the ready state. Am I wrong in so thinking? Dan
No InterruptedException is actually thrown in this code. Each sleep() method completes normally, after which it has reached the end of the try{} block, so it skips over the catch{} block to the first code after the try/catch, which is a print statement. Each print statement will be executed whether an exception is thrown or not.
"I'm not back." - Bill Harding, Twister
Dan Temple
Ranch Hand
Joined: Jul 10, 2001
Posts: 93
posted
0
God I am such an idiot ... for some reason, my brain saw that output as being inside the catch block. Sorry about that ... Dan
Which brings up the touchy issue about coding style. if the catch had been coded:
It would have been MUCH easier for you to see that the println was AFTER it.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
It also brings up the importance of using proper indentation, and [ code ] tags to preserve this indentation at JavaRanch. Actually I see that Dan's original source was indented properly - it's just the [ code ] tags that are missing. Personally I think it's perfectly well readable with the proper indentation, without putting the braces on separate lines. But it's all a matter of what style you're used to, I think...
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.