主方法关闭后如何运行线程?

Tru*_*ePS 12 java multithreading

这是我的两个班级:

public class Firstclass {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Main start....");
        Secondclass t1 = new Secondclass();
        t1.setName("First Thread");
        Secondclass t2 = new Secondclass();
        t2.setName("Second Thread");
        t1.start();
        t2.start();
        System.out.println("Main close...");
    }
}
Run Code Online (Sandbox Code Playgroud)

public class Secondclass extends Thread {
    @Override
    public void run() {
        try {
            loop();
        } catch(Exception e) {
            System.out.println("exception is" + e);
        }
    }

    public void loop() throws InterruptedException {
        for(int i = 0; i <= 10; i++) {
            Thread t = Thread.currentThread();
            String threadname = t.getName();
            if(threadname.equals("First Thread")) {
                Thread.sleep(1000);
            } else {
                Thread.sleep(1500);
            }
            System.out.println("i==" + i);   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我运行时Firstclass,输出是:

Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10
Run Code Online (Sandbox Code Playgroud)

我的第一个问题是:我想知道为什么即使main方法已经完成,两个线程仍在运行?

我的第二个问题是:任何人可以向我解释方法join和方法之间的区别synchronized吗?

Old*_*eon 0

您的main话题尚未关闭 -

      // ...
      System.out.println("Main close...");
      // <--- Your main method is here while all the other threads complete (sort of).
     }
Run Code Online (Sandbox Code Playgroud)

join关于你的问题的第二部分 -和之间没有联系synchronized。他们几乎是相反的。

  • join- 等待线程完成后再恢复。
  • synchronized- 只有一个线程可以进入这里,所有其他线程必须等待。

  • -1。方法“main”将*不会*等到所有线程完成,除非您显式使用“join”。不过,在所有用户线程完成之前,JVM 不会结束该进程。 (5认同)