執行緒的三種建立方式

2021-10-23 18:28:01 字數 1109 閱讀 2789

執行緒的建立包括三種方式:

1.繼承thread類,重寫run方法;

2.實現runnable介面,重寫runnable方法;

3.實現callable介面,重寫call方法。

只需繼承thread類,重寫run方法,將子執行緒即將進行的業務新增至run方法中實現即可。

public class diythread extends thread

public static void main(string args)

}

可直接實現runnable介面,或者建立runnable例項,重寫run方法。

public class diyrunnable implements runnable

public static void main(string args)

}

或者

public static void main(string  args)

};//啟動方法:建立類物件,將runnable作為引數傳入,呼叫strat方法即可

thread thread=new thread(runnable);

thread.start();

}

與前兩者有較大的區別,使用callable介面實現建立子執行緒,有返回值,需要繼承時定義泛型,最為返回值的型別。

public static class diythread implements callable

}public static void main(string args) catch (interruptedexception e) catch (executionexception e)

executorservice.shutdown();

}

1.runnable介面無返回值,callable有返回值;

2.runnable介面重寫run()方法,callable重寫call()方法;

3.callable介面需要拋異常,runnable不用;

4.callable任務可以得到乙個futuretask物件,表示非同步計算的結果。

執行緒 三種方式 建立執行緒

第一種 1 模擬龜兔賽跑 繼承thread 重寫run 執行緒體 2 使用執行緒 建立子類物件 物件.strat 執行緒啟動 author administrator public class rabbits extends thread class tortoise extends thread ...

執行緒的三種建立方式

public class web12306 多執行緒的三種方式 class threadtest01 extends thread class threadtest02 implements runnable class threadtest03 implements callable return...

建立執行緒的三種方式

一 是繼承thread方法 public class mythread extends thread private void dosomething public class newthread private static void dosomething 二 是實現runnable介面 使用r...