java 主線程與子線程

在JAVA的main函數中,開啓一個子線程時,主線程會執行下去,不會等待子線程執行,但是隻有子線程執行完畢後,JVM才退出。

調用 join 方法,可以使主線程等待 子線程運行完畢之後再執行

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("主線程結束");

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章