thread.join()

thread.join()主線程需要等待子線程執行完成之後再結束

public class TestDemo {
    public static void main(String[] args) {
        try {
            Test.calc();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Test{
    private long count=0;
    public long  add10K(String id ){
        int i=0;
        while (i++<1000000){
            count+=1;
        }
        System.out.println(id+" count:"+count);
        return count;
    }
    public static long  calc() throws Exception{
        Test test = new Test();
        Thread thread1 = new Thread(()->{
            test.add10K("1");
        });
        Thread thread2 = new Thread(()->{
            test.add10K("2");
        });
        thread1.start();
        System.out.println("1");
        thread2.start();
        System.out.println("2");
        thread1.join();
        System.out.println("3");
        thread2.join();
        System.out.println("4");
        return 1;
    }
}

 

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