Java Threading Concept Understanding

Posted by Nirmal on Stack Overflow See other posts from Stack Overflow or by Nirmal
Published on 2010-06-16T07:08:59Z Indexed on 2010/06/16 7:12 UTC
Read the original article Hit count: 466

Filed under:
|
|
|

Hello All...

Recently I have gone through with one simple threading program, which leads me some issues for the related concepts... My sample program code looks like :

class NewThread implements Runnable {
    Thread t;
    NewThread() {
        t = new Thread(this, "Demo Thread");
        System.out.println("Child thread: " + t);
        t.start(); // Start the thread
    }
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
        System.out.println("Exiting child thread.");
    }
}
class ThreadDemo {
    public static void main(String args[]) {
        new NewThread(); // create a new thread
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println("Main Thread: " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        System.out.println("Main thread exiting.");
    }
}

Now this program giving me the output as 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.

So, that's very much clear to me. But as soon as I am replacing the object creation code (calling of a NewThread class constructor) to as follows :

NewThread nt = new NewThread(); // create a new thread

the output becomes a bit varied like as follows :

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Child Thread: 3
Main Thread: 4
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

And some times it's giving me same output in both the cases. So, i am not getting the exact change in both the scenario.

I would like to know that you the variation in the output is coming here ?

Thanks in advance...

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading