執行緒建立的三種方式

2021-09-13 23:47:16 字數 1930 閱讀 3246

1. 繼承thread類

第一步:定義乙個類繼承thread類,並且重寫run方法,返回值型別為void;

第二步:直接建立thread繼承類物件;

第三步:繼承類物件呼叫start方法;

**舉例:

public static void main(string args) throws ioexception   catch (interruptedexception e) 

} class mythread2 extends thread catch (interruptedexception e)

system.out.println("執行緒"+thread.currentthread().getname()+"執行完畢");

}}

2.實現runnable介面

第一步:定義乙個類實現runnable介面,並重寫run方法,返回值型別為void;

第二步:建立thread類的物件;

第三步:建立實現介面類物件,並將此物件作為引數傳遞給thread類的建構函式;

第四步:thread類物件呼叫start方法;

**舉例:

public static void main(string args)   

class runner1 implements runnable

} }

3.實現callable介面

第一步:定義乙個類實現callable介面,並實現call方法,返回值型別不為空;

第二步:建立thread類物件;

第三步:建立實現介面類的例項,並利用futuretask物件包裝此例項;

第四步:futuretask物件作為引數傳遞給thread類;

第五步:thread類物件呼叫start方法;

**舉例:

private int i = 10;

private object object = new object();

@suppresswarnings()

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

} @suppresswarnings("rawtypes")

class mythread3 implements callable catch (interruptedexception e)

system.out.println("執行緒"+thread.currentthread().getid()+"睡眠結束");

i++;

system.out.println("i:"+i);

}return 0;

}}

三者的區別:

繼承thread

實現runnable

實現callable

實現方式

執行緒**存放在thread子類run方法中

執行緒**存放在介面的子類的run方法中

執行緒**存放在介面的子類的call方法中

優勢編寫簡單,可直接用this.getname()獲取當前執行緒,不必使用thread.currentthread()方法。

避免了單繼承的侷限性、多個執行緒可以共享乙個target物件,非常適合多執行緒處理同乙份資源的情形。

有返回值、避免了單繼承的侷限性、多個執行緒可以共享乙個target物件,非常適合多執行緒處理同乙份資源的情形。

劣勢已經繼承了thread類,無法再繼承其他類。

比較複雜、訪問執行緒必須使用thread.currentthread()方法、無返回值。

比較複雜、訪問執行緒必須使用thread.currentthread()方法。

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

第一種 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...