Understand the concept of MultiThreading in Java -


Recently I have gone through a simple threading program, which gives me some issues for related concepts. .. My sample program code looks like this:

class executes NewThread Runnable {Thread T; Newtread () {t = new thread (this, "demo thread"); System.out.println ("hair thread:" + T); T.start (); // start the thread} Public Zero Run (try {for (i) i try the (); {-};} {System.out.println ("child thread:" + i); Thread.Sleep (500); }} Grip (Interrupted ejection) {System.out.println ("Child Interrupted."); } System.out.println ("The child's thread is coming out."); }} Class thread dumo {public static zero main (string argument []) {new Newread (); // Try creating a new thread {for (int i = 5; i & gt; I;) {System.out.println ("main thread:" + i); Thread.Sleep (1000); }} Grip (Interrupted e) E. {System.out.println ("Main thread interrupted."); } System.out.println ("The main thread goes out."); }}

Now this program gives me the output as:

  hair thread: thread [demo thread, 5, main] main thread : 5 children thread: 5 hair thread: 4 main thread: 4 hair thread: 3 hair thread: 2 main thread: 3 hair thread: 1 hair thread is coming out. Main thread: 2 main thread: 1 main thread emerges.  

So, this is very clear to me, but as soon as I am replacing the object creation code (calling the neutath class constructor) such as:

  NewThread nt = newThread (); // Create a new thread  

The output is slightly different as follows:

  Child thread: thread [demo thread, 5, main] Main thread: 5 hair thread: 5 hair thread: 4 hair thread: 3 main thread: 4 hair thread: 2 hair thread: 1 main thread: 3 hair thread turned out. Main thread: 2 main thread: 1 main thread emerges.  

And sometime it is giving me the same output in both cases. Therefore, I am not getting the exact change in both scenarios.

Would you like to know that the output is different?

Thank you in advance ...

Outputed OS process scheduling and JVM Thread scheduling is due to the nature of both. Even if you take the second thread, then there is no guarantee that your thread will wake up only after 500 mms.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -