Note that there are some explanatory texts on larger screens.

plurals
  1. POmulithreading in java example
    primarykey
    data
    text
    <p>Here is a sample program in java from <a href="http://www.tutorialspoint.com/java/java_multithreading.htm" rel="nofollow">tutorials point</a>:</p> <pre><code>// Create a new thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i &gt; 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a 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 a new thread try { for(int i = 5; i &gt; 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."); } } </code></pre> <p>The output of the program is as follows.</p> <pre class="lang-none prettyprint-override"><code>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. </code></pre> <p>I have trouble understanding why the main thread is executing before the child thread. In the program you can see that first new NewThread() is executed. The NewThread class instantiates a new thread and calls the start() function on the new thread which then calls the run() function. The loop in the main function comes only after a new thread is created. However when the program is run , The loop in the main thread is run before the child thread. Please help me understand.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload