2

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

Bick
  • 15,895
  • 44
  • 133
  • 231
  • 1
    possible duplicate of [What is the difference between Thread.start() and Thread.run()?](http://stackoverflow.com/questions/2674174/what-is-the-difference-between-thread-start-and-thread-run) – user253751 Aug 02 '14 at 11:05

1 Answers1

7

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.

Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123
  • @rails, in other words: start() is the method that _you_ call to start the thread, and run() is the method that _the thread_ calls to do whatever it was that you wanted the thread to do. – Solomon Slow Aug 02 '14 at 15:17