執行緒的實現方式

2021-08-08 09:48:29 字數 1622 閱讀 9594

建立執行緒的兩種方式

1、繼承thread類建立執行緒

thread類本質上是實現了runnable介面的乙個例項,代表乙個執行緒的例項。啟動執行緒的唯一方法就是通過thread類的start()例項方法。start()方法是乙個native方法,它將啟動乙個新執行緒,並執行run()方法。這種方式實現多執行緒很簡單,通過自己的類直接extend thread,並複寫run()方法,就可以啟動新執行緒並執行自己定義的run()方法。例如:

public

class mythread extends

thread

}

mythread mythread1 = new

mythread();

mythread mythread2 = new

mythread();

mythread1.start();

mythread2.start();

2、實現runnable介面建立執行緒

如果自己的類已經extends另乙個類,就無法直接extends thread,此時,可以實現乙個runnable介面,如下:

public

class mythread extends otherclass implements

runnable

}

為了啟動mythread,需要首先例項化乙個thread,並傳入自己的mythread例項:

mythread mythread = new

mythread();

thread thread = new

thread(mythread);

thread.start();

事實上,當傳入乙個runnable target引數給thread後,thread的run()方法就會呼叫target.run(),參考jdk源**:

public

class thread implements runnable

/*** allocates a new object. this constructor has the same

* effect as

* , where is a newly generated

* name. automatically generated names are of the form

* n, where n is an integer.

** @param  target

*         the object whose method is invoked when this thread

*         is started. if , this classes method does

*         nothing.

*/public thread(runnable target)

public

void

run()

}

}
兩種方式都不能使用stop()方法讓執行緒消亡,只能讓run()方法自然結束才算消亡

執行緒的實現方式

執行緒的實現可以分為兩類 使用者級執行緒 user levelthread,ult 和核心級執行緒 kemel levelthread,klt 核心級執行緒又稱為核心支援的執行緒。在使用者級執行緒中,有關執行緒管理的所有工作都由應用程式完成,核心意識不到執行緒的存在。應用程式可以通過使用執行緒庫設計...

多執行緒的實現方式

什麼時候需要使用多執行緒 1.通過平行計算提高程式效能 2.等待網路 io響應導致的耗時問題 多執行緒的實現有三種 一 繼承thread類 thread類本質上是實現了runable介面的乙個例項,它代表了乙個執行緒的例項。啟動執行緒唯一的方法 是通過thread類的start 方法。start方法...

多執行緒實現方式

多執行緒實現方式 1 繼承thread類建立執行緒 thread類本質上是實現了runnable介面的乙個例項,代表乙個執行緒的例項。啟動執行緒的唯一方法就是通過thread類的start 例項方法。start 方法是乙個native方法,它將啟動乙個新執行緒,並執行run 方法。這種方式實現多執行...