建立執行緒的三種方式,對比其優劣勢

2021-08-17 05:19:11 字數 1494 閱讀 2592

public class createthreadmethod 

});thread threadthree = new thread(stringfuturetask);

threadthree.start();

string resstr = stringfuturetask.get();

system.out.println(resstr);

/**實現callable

介面*/

futuretaskfuturetask = new futuretask<>(new createthreadthree());

thread threadthreeclass = new thread(futuretask);

threadthreeclass.start();

string str = futuretask.get();

system.out.println(str);}}

/*** 建立執行緒的第一種方式,繼承thread類

*/class createthreadone extends thread

}/**

* 建立執行緒的第二種方式,實現runable,可以多實現,單繼承(優勢)

* 第二種方式將執行緒物件和執行緒任務物件分離開。降低了耦合性,利於維護

*/class createthreadtwo implements runnable

}class createthreadthree implements callable

}

建立執行緒的三種方式的對比

採用實現runnable、callable介面的方式創見多執行緒時,優勢是:

執行緒類只是實現了runnable介面或callable介面,還可以繼承其他類。

在這種方式下,多個執行緒可以共享同乙個target物件,所以非常適合多個相同執行緒來處理同乙份資源的情況,從而可以將cpu、**和資料分開,形成清晰的模型,較好地體現了物件導向的思想。

劣勢是:

程式設計稍微複雜,如果要訪問當前執行緒,則必須使用thread.currentthread()方法。

使用繼承thread類的方式建立多執行緒時優勢是:

編寫簡單,如果需要訪問當前執行緒,則無需使用thread.currentthread()方法,直接使用this即可獲得當前執行緒。

劣勢是:

執行緒類已經繼承了thread類,所以不能再繼承其他父類。

建立執行緒最底層是呼叫threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,blockqueueworkqueue)

corepoolsize 最大的執行執行緒 核心執行緒數

maximumpoolsize 最大的建立執行緒數

keepalivetime 超時時間,如果在該時間內該執行緒沒用被使用,就**至執行緒池中

timeunit 時間單位

workqueue 阻塞佇列(執行緒復用的關鍵)

三種光網路佈線技術的優劣勢對比分析

光纖在各種光網路中的實際應用決定了對光纖技術效能的要求。對於短距離光傳輸網路,考慮的重點是適合雷射傳輸和模式頻寬更寬的多模光纖,以支援更大的序列訊號資訊傳輸容量。下面是當前三種網路技術的介紹 1 fddi cddi 光纖 銅線分布式資料介面 這是一種成熟的 非載波偵聽的 100m頻寬共享的網路技術。...

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

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