java - Is it possible to exit the RUNNABLE state without having executed a single instruction? -


i'm reading book oracle certified professional java se 7 programmer exams 1z0-804 , 1z0-805. 1 of question asks output of code

class threadtest {     public static void main(string []args) throws interruptedexception {         thread t1 = new thread() {             public void run() { system.out.print("t1 "); }         };         thread t2 = new thread() {             public void run() { system.out.print("t2 "); }         };         t1.start();         t1.sleep(5000);         t2.start();         t2.sleep(5000);         system.out.println("main ");     } } 

the book says output t1 t2 main because timed_waiting state can reach runnable state.

but thinking thread can exit runnable state without having executed single instruction.

the doc says:

a thread in runnable state executing in java virtual machine may waiting other resources operating system such processor.

is answer of book correct? , possible exit runnable state without having executed single instruction?

i don't believe book correct, different reasons.

first off let's deal question directly. way change out of runnable state executing instruction results in state changing. instruction might call method (which happens synchronized , thread waits lock in blocked) or return run() method (causing thread become terminated). these state changes happen because thread has done change own state.

edit - elaberate on this; method public void run() {} contains precisely 1 instruction: return. thread must execute return runnable terminated.

the book wrong (sort of). in "normal cases" 5 seconds long enough kick off thread. there nothing synchronizing threads , nothing forcing threads things in particular order.

the flow is:

  1. the main thread kicks off t1.
  2. the main thread goes sleep 5 seconds. you hope 5 seconds long enough os start thread, there no guarantee will. if os under attack fork bomb might not have resources start new thread.
  3. the main thread kicks off t2. if os clogged , t1 hasn't started yet, there's no guarantee t2 not start (execute code) first.
  4. the main thread goes sleep 5 seconds.
  5. the main thread prints "main ". again if os clogged up, might happen before t1 or t2 start.

never rely on sequence of multiple threads without using synchronization!


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -