views:

94

answers:

2
class Name implements Runnable {
    public void run() {
        for (int x = 1; x <= 3; x++) {
            System.out.println("Run by "
                               + Thread.currentThread().getName()
                               + ", x is " + x);
        }
    }
}
public class Threadtest {
    public static void main(String [] args) {
        // Make one Runnable
        Name nr = new Name();
        Thread one = new Thread(nr);
        Thread two = new Thread(nr);
        Thread three = new Thread(nr);
        one.setName("A");
        two.setName("B");
        three.setName("C");
        one.start();
        two.start();
        three.start();
    }
}

The answer is different while compiling and running more then one time I don't know why? any idea.

+7  A: 

It should show the same output, but potentially in a different order for each run.

You've got three independent threads: each will show three lines of output, in the obvious order - but there's no guarantee which thread will execute first, etc. In this particular case I don't believe you've got any side effects which would cause truly strange behaviour - just the normal ambiguity of which threads will run when. Note that on a multicore processor the threads are likely to be running simultaneously - the only synchronization is whatever happens within System.out.println.

Jon Skeet
thanks , jon I have no experience in thread.
Sanjeev
+1  A: 

one of them will start running first then the second and lastly the third . that is depend on thread scheduler on system

Wajdy Essam
There's nothing to make the second run *when the first finishes*. All three threads can be running in parallel.
Jon Skeet
i know that, but i not meant finish all processing, but finish it execution time then scheduler pick another thread to work. threads working in semi-parallel not true parallel processing.
Wajdy Essam
@Wajdy: That depends on how many cores you've got. If you're using a machine with multiple processors, they're likely to be using "true parallel processing". You might want to edit your answer to be clearer...
Jon Skeet