concurrency - mulithreading in java example -


here sample program in java tutorials point:

// create new thread. class newthread implements runnable {    thread t;    newthread() {       // create new, second thread       t = new thread(this, "demo thread");       system.out.println("child thread: " + t);       t.start(); // start thread    }     // entry point second thread.    public void run() {       try {          for(int = 5; > 0; i--) {             system.out.println("child thread: " + i);             // let thread sleep while.             thread.sleep(50);          }      } catch (interruptedexception e) {          system.out.println("child interrupted.");      }      system.out.println("exiting child thread.");    } }  public class threaddemo {    public static void main(string args[]) {       new newthread(); // create new thread       try {          for(int = 5; > 0; i--) {            system.out.println("main thread: " + i);            thread.sleep(100);          }       } catch (interruptedexception e) {          system.out.println("main thread interrupted.");       }       system.out.println("main thread exiting.");    } } 

the output of program follows.

child thread: thread[demo thread,5,main] main thread: 5 child thread: 5 child thread: 4 main thread: 4 child thread: 3 child thread: 2 main thread: 3 child thread: 1 exiting child thread. main thread: 2 main thread: 1 main thread exiting. 

i have trouble understanding why main thread executing before child thread. in program can see first new newthread() executed. newthread class instantiates new thread , calls start() function on new thread calls run() function. loop in main function comes after new thread created. when program run , loop in main thread run before child thread. please me understand.

the loop in main thread run before child thread. please me understand.

threads not have any form of synchronization default , can run in order executions possibly interleaving. can acquire locks , use ensuring order, example if main thread acquires lock before starting child thread, having child thread wait acquire lock, , having main thread release lock once it's done tasks.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -