java main thread and the child thread

在JAVA的main函数中,开启一个子线程时,主线程会执行下去,不会等待子线程执行,但是只有子线程执行完毕后,JVM才退出。

After calling again join execution method, the main thread can wait for the child thread has finished running

public class ThreadTest {

    static public  int a = 0; //定义一个静态变量
    public static void main(String[] args) throws InterruptedException {
		//创建子线程
        Thread thread = new Thread(new Runnable() {
            public void run() {
                while (a < 20) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    a++;
                    System.out.println("这里内部线程" + a);
                }
            }
        });
        thread.start();
        thread.join();//主线程等待子线程结束
        
        Thread.sleep(5000);
        System.out.println(a);
        System.out.println("主线程结束");

    }
}

Published 32 original articles · won praise 1 · views 1175

Guess you like

Origin blog.csdn.net/ASYMUXUE/article/details/104541936