3

I must be missing something:

public class Test {
    public static void main(String[] args) {
        (new Thread(new Action())).run();
        System.out.println("Blah");
    }
}

class Action implements Runnable {
    public void run() {
        while (true) {

        }
    }
}

I make a thread that is supposed to be running a loop.

In my main thread I print "Blah".

However, it is never printed. Why not? If I made a separate thread, it shouldn't affect my main execution thread, right?

This machine has four cores.

Saturn
  • 17,888
  • 49
  • 145
  • 271

2 Answers2

11

Call start() instead of run() to start a thread.

Simply calling run() means a method call with infinite loop in the same main thread that will block the next statement written in main thread.

Have a look at Java Tutorial on Defining and Starting a Thread


I should be (new Thread(new Action())).start(); to start a thread but still it will create an infinite loop and the new started thread will never stop.

Try with Thread.currentThread().getName() to confirm it again as shown below:

public void run() {
    System.out.println(Thread.currentThread().getName()); // output "main"
}

A Pictorial Representation of Thread Life-cycle along with it's methods

enter image description here

Braj
  • 46,415
  • 5
  • 60
  • 76
6

Because you are not invoking start(), you are calling directly the implementation method of the thread run(), thus no thread is started, code is just executed.

run() is the method called by the thread internal structure to execute the task, since it's just a normal method which doesn't have anything attached.

Jack
  • 131,802
  • 30
  • 241
  • 343