執行緒傳統技術

2021-10-11 02:04:26 字數 2601 閱讀 7924

1.實現thread類建立執行緒

public

class

mythread

extends

thread

}

mythread mythread1 =

newmythread()

; mythread mythread2 =

newmythread()

; mythread1.

start()

; mythread2.

start()

;

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

public

class

mythread

extends

otherclass

implements

runnable

}

3.執行緒中的方法sleep(),currentthread(), getid(), isalive(), yield() , setpriority() , setdaemon(),wait(),join(),notify()

sleep()方法

作用: sleep()方法用於在指定的毫秒內讓執行緒休眠,即暫停執行。

thread.sleep(1000);

currentthread()方法

作用:返回**段正在被哪個執行緒呼叫

thread.

currentthread()

.getname

()

getid()方法

作用:獲取執行緒的唯一id

thread.

currentthread()

.getid

()

yield()方法

方法的作用是放棄當前的cpu的資源。但是放棄的時間是不確定的。有可能剛放棄,馬上又獲得了cpu的時間片

setpriority() 執行緒的優先順序

執行緒的優先順序較高的則優先獲得cpu資源。

優先順序劃分從1-10,如果小於1或者大於10則會丟擲異常

優先順序具有繼承特性,例如如果執行緒a的優先順序設定為6,如果在a執行緒中啟動b執行緒,則b執行緒的優先順序也為6

join()方法

在很多情況下,主線程建立並啟動了執行緒,如果子執行緒中要進行大量耗時運算,主線程往往將早於子執行緒結束之前結束。這時,如果主線程想等待子執行緒執行完成之後再結束,比如子執行緒處理乙個資料,主線程要取得這個資料中的值,就要用到join()方法了。方法join()的作用是等待執行緒物件銷毀。

public

class

joinmethod

extends

thread

catch

(interruptedexception e)

} system.out.

println

(thread.

currentthread()

.getname()

+":"

+i);}}

@override

public

void

run()}

public

joinmethod

(string name)

}

wait()、wait(long millis)、wait(long millis,int nanos):讓當前執行緒進入等待狀態,執行緒在獲取物件鎖後,主動釋放物件鎖,同時本執行緒休眠。

join()、join(long millis)、join(long millis,int nanos):把指定的執行緒加入到當前執行緒,等待指定執行緒終止。

wait()和notify(),notifyall()是object類的方法,需要在synchronized語句塊內使用;sleep()、yield()、join()是thread類的方法。

notify()隨機喚醒執行緒,notifyall()喚醒所有執行緒

package cn.itcast.heima2;

public

class

traditionalthread

catch

(interruptedexception e)

system.out.

println

("1:"

+ thread.

currentthread()

.getname()

);}}

};thread.

start()

; thread thread2 =

newthread

(new

runnable()

catch

(interruptedexception e)

system.out.

println

("1:"

+ thread.

currentthread()

.getname()

);}}

}); thread2.

start()

;}

傳統多執行緒技術

執行緒有2種方式 1 重寫thread的run方法 例子 new thread start 2 thread中構造方法有帶引數的傳入runable 推薦 例子 new thread new runable public void run start 解釋 thread類中的run方法 為 priva...

傳統執行緒技術(一)

一.傳統執行緒建立方法 1.覆蓋thread子類的run方法中編寫詳細 2.在傳遞給thread的runnable物件的run方法中編寫詳細 二.實現 public class traditionalthread catch interruptedexception e thread1.start ...

傳統執行緒同步通訊技術

什麼是執行緒同步通訊呢?其實簡單來說就是執行緒間的等待與喚醒 下面我們來了解一下 1.簡單多執行緒通訊 現在有a b執行緒,讓執行緒a先執行10次迴圈,隨後讓執行緒b執行20次,之後反覆100次 該如何實現呢?需要注意哪些問題?如下 public class main start new threa...