I have the following code on threads.I have a doubt that is it possible that any of the two threads created ie one and two will execute the 2nd print statement in run method before the first print statement in it?That is print hello first and then the current thread name

public class HelloWorld {

     public static void main(String []args){
        System.out.println("Hello World");
        Runnable r = new Animal();
        Thread t =new Thread(r);
        Thread t1 =new Thread(r);
        t.start();
        t.setName("one"); 
        t1.start();
       t1.setName("two");
        System.out.println(Thread.currentThread().getName());
     }
} 

class Animal implements Runnable{

public void run(){

System.out.println(Thread.currentThread().getName());
System.out.println("hello");

}


}

try running the code a hundred times after each other, you'll see.

I mean to say that is it possible for a thread to execute a 2nd statement before the 1st statement as in the following code lines
1st statement
2nd statement...The reason for this doubt is that the normal execution always goes line by line as in 1st statement will be executed and then 2nd and not vice versa..

Edited 3 Years Ago by saurabh.mehta.33234

Within a single thread statements will be executed in the correct order. Between two different threads there are no guaarantees unless you explicitly synchronise.

Edited 3 Years Ago by JamesCherrill

Within a single thread statements will be executed in the correct order

So you mean to say that if I have only one thread lets say "one" and in run() I have

System.out.println(Thread.currentThread().getName());
System.out.println{"hello"};

Then it is not possible to have output as:
hello
one

Is this you meant to say?? And incase if I have two threads one and two and same run() Then the output can be:
hello
one
hello
two

ehm, no. the first print 'll always be either 'one' or 'two'.
it's the order in which the following prints appear that can differ.

let's say you have two Threads running, you can not predict which thread 'll run first, or when there 'll be switched between the threads, but you do know for sure, that when in these Threads you run the next lines:

System.out.println(Thread.currentThread().getName());
System.out.println{"hello"};

that the very first line to be printed will be printed by the line:
System.out.println(Thread.currentThread().getName());

and the very last line 'll be
"hello"

everything in between those two, can not be predicted

That's right for one thread. With two threads you could see

one
two
hello
hello

or

two
hello
one
hello

or

two
one
hello
hello

ehm, no. the first print 'll always be either 'one' or 'two'.
it's the order in which the following prints appear that can differ.

@stultuske Thank you for your response So to conclude you mean to say that whether it be single thread or more than one thread the 2nd printf can never execute before 1st printf??

what happens inside one singular Thread, will always happen in the order in which it is written. (unless of course you start other Thread(s) in there)

in your example:

System.out.println(Thread.currentThread().getName());
System.out.println{"hello"};

the first line printing the Thread-name will (for each Thread) ALWAYS be printed first, and the "hello" part, always last.

but, when you are working with two Threads simultaneously, the 2nd print can be two things:
1. the "Hello" of the first Thread, finishing with it's task
2. the name of the second Thread.

JamesCherrill pointed out all the possible options.

as I said earlier: all you can be sure of, is that the first print on your screen will be caused by this line:
System.out.println(Thread.currentThread().getName());
and the very last of the block will be printed by:
System.out.println{"hello"};

you don't know which Thread 'll actually start first, but no matter which one: since that line 'll be executed first, the first line can be predicted.
The same is with the last line. you don't know which Thread 'll run the longest, but no matter which Thread ends last, they all end with printing "hello", so only the two lines in between can vary between the name of a Thread and "hello"

What everyone is tap-dancing around is that, in order to get a consistent result, you need to synchronize the threads. This means that there would have to be an object which has a synchronized() block associated with it, which acts as a lock on that object - other threads cannot access that object until after the lock is released.

Here I have an example, derived from your code but now quite different, which demonstrates thread synchronization:

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class SyncedHelloWorld {

    public static void main(String []args){
        ArrayList<Greeting> g = new ArrayList<Greeting>();

        g.add(new Greeting("Hello"));
        g.add(new Greeting(", "));
        g.add(new Greeting("World!"));
        g.add(new Greeting("\n"));

        Thread[] t = new Thread[Greeting.Count()];

        for (int i = 0; i < Greeting.Count(); i++) {
            t[i] = new Thread(g.get(i));
            t[i].start();
        }
        try {
            for (int i = 0; i < Greeting.Count(); i++) {
                t[i].join();
            }
        }
        catch (InterruptedException e) {
            // do nothing
        }

    }
} 

class Greeting implements Runnable {
    private final String phrase;
    private final int index;
    private static int count = 0;

    // The object position must be an AtomicInteger, as
    // it needs to be mutable. Ordinary Integer objects
    // generate new objects in auto-boxing, and the method 
    // would not have a lock on the new object.
    private static AtomicInteger position = new AtomicInteger(0);    

    public Greeting(String newPhrase) {
        phrase = newPhrase;
        index = count++;
    }

    public static int Count() {
    return count;
    }

    public void run() {
        synchronized(position) {
            for (int i = 0; i < count; i++) {
                // loop until the correct 
                // position is reached
                while (index != position.get()) {
                    try {
                        position.wait();
                    }
                    catch (InterruptedException e) {
                        // do nothing
                    }
                }
                System.out.print(phrase);
                position.set((position.get() + 1) % count);
                position.notifyAll();
            }   
        }
    }
}

Note that there's a lot of extra code, most of which is related to the synchronization. In this case, I generalized the Greeting class so that it automatically tracks the order in which the Greetings were created, and uses that order to determine which one goes at a given time.

Edited 3 Years Ago by Schol-R-LEA

nobody is tapdancing around anything, that synchronized threads 'll lead to different results has been mentioned already.
the question at hand was: explain why this code can behave like this, not : how will other code (possibly) behave.

This question has already been answered. Start a new discussion instead.