Why is this thread affecting the main thread?

前端 未结 2 1369
南旧
南旧 2020-12-19 20:43

I must be missing something:

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


        
2条回答
  •  独厮守ぢ
    2020-12-19 21:01

    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

提交回复
热议问题