獲取當前執行緒 :currentthread()
該方法返回執行currentthread()這個方法當前執行緒的資訊(返回的是thread例項)。
使用這個方法可以獲取執行緒的名稱等;
下面來看一下比較複雜的例子:
輸出結果:public
class
threadmethodtest
@override
public
void
run()
}public
static
void
main(string args)
}
執行緒啟動:start()和run()mythread-start
thread
.currentthread().getname():main //這個時候執行緒還沒建立,所以還是main執行緒執行
this.getname():thread-0
//這裡獲取的這個類預設的名字
mythread-end
run-start
thread
.currentthread().getname():mythread
this.getname():mythread
run-end
main
呼叫run()不會啟動執行緒
呼叫start()才會啟動乙個執行緒。
iaalive() 判斷執行緒是否處於存活狀態:
sleep方法public
class
threadtest
}public
static
void
main(string args) throws interruptedexception
}
讓執行緒休眠(單位毫秒)
和object方法wait區別():
sleep 讓執行緒從 【running】 -> 【阻塞態】 時間結束/interrupt -> 【runnable】
wait 讓執行緒從 【running】 -> 【等待佇列】notify -> 【鎖池】 -> 【runnable】
getid()方法
取得執行緒唯一標識
暫停執行緒:resume和suspend
暫停正在執行的方法執行緒。
他們都是獨佔的方式占用公共物件,會是的其他執行緒無法訪問公共同步物件。
yield 方法和join方法
yeild方法
join
- 與yield相反,這個方法阻塞呼叫此方法的執行緒(calling thread),直到執行緒t完成,此執行緒再繼續;通常用於在main()主線程內,等待其它執行緒完成再結束main()主線程。例如:
- 假設有a、b兩個執行緒,通常是在a執行緒中呼叫b執行緒變數的join方法,表示讓a先執行完,再執行b。
9. setpriority 設定執行緒優先順序。
多執行緒系列(三) 執行緒池基礎
目錄 一 為什麼要使用執行緒池 執行緒池概念理解 備註 執行緒池中的執行緒是後台執行緒。1 為什麼會有執行緒池?因為建立執行緒和銷毀執行緒相對來說需要消耗大量的時間和資源。太多的執行緒會浪費記憶體。2 執行緒池是什麼?執行緒池就是乙個可持續性發展的執行緒集合,執行緒池內部維護著乙個訊息佇列。當一條方...
多執行緒三 執行緒中常用的函式
1.sleep 1.1 執行緒睡眠 thread.sleep long millis 方法,使執行緒轉到阻塞狀態。millis引數設定睡眠的時間,以毫秒為單位。當睡眠結束後,就轉為就緒 runnable 狀態。當前執行緒 即呼叫該方法的執行緒 暫停執行一段時間,讓其他執行緒有機會繼續執行,但它並不釋...
Linux多執行緒學習(三)執行緒屬性
執行緒的建立函式pthread creat的第二個引數為pthread attr t型別的指標 預設屬性建立執行緒時賦值null pthread attr t是乙個結構體型別,定義如下 typedef struct pthread attr t 執行緒屬性的使用步驟 建立屬性物件 以預設值初始化屬性...