線程拼接join函數

假設線程需要另一個線程的處理的返回值;然後該線程繼續完成自己的任務;需要使用join()函數;

就是加入一個線程,讓加入的線程先執行,有點類似順序執行的味道

public class MyJoin {
    public static void main(String[] args) throws InterruptedException {
        ThedJoin myj=new ThedJoin(3);
        myj.start();
        myj.join();
        System.out.println(myj.getResult());
    }
}

//需要獲取

class ThedJoin extends Thread{
    int a;
    int result;
    public ThedJoin(int a) {
       this.a=a;
    }
    public int getResult() {
        return result;
    }
    
    @Override
    public void run() {
        
        try {
            Thb thb=new Thb(5);
            thb.start();
//            thb.join();
            Thread.sleep(10);//等效語句
            int b=thb.getB();

            //3+5+10
            result=a+b;    
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

class Thb extends Thread{
    int b;
    public Thb(int c) {
        b=c;
    }
    
    @Override
    public void run() {
        b+=10;
    }
    
    public int getB() {
        return b;
    }
}
 

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