Bick
Bick

Reputation: 18511

java - Why the thread execution was finished before the next line was executed

I am writing a simple algorithm in a new thread. I wonder why the code that follows waits until the thread is finished in order to run. Here is a simple program that does the same.

public static void main(String[] args) {
    final String[] strings = new String[10];

    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                strings[i] = String.valueOf(i);
                Thread.sleep(10000); // in real code this is wrapped in a simple try catch
            }
        }
    }).run();

    for (String string : strings) {
        System.out.print(string);
    }
}

The thread sleeps 10 seconds and yet the last iteration was executed after the thread finished running.
I can even extend the sleep time. but the next line (the final iteration) is not executed until the thread finished.
Why is that?

The result is 0 1 2 3 4 5 6 7 8 9

Upvotes: 2

Views: 1056

Answers (1)

Juned Ahsan
Juned Ahsan

Reputation: 68715

You are not spawning a thread as you just call run method directly. You need to call start method instead.

When you call start method, JVM spawns a new thread and calls the run method of the Runnable object. Calling run method directly is similar to calling any other normal method, no new thread.

Upvotes: 7

Related Questions