多執行緒 知識點集合

2021-09-02 20:10:58 字數 1972 閱讀 2192

執行緒常用方法

new——新建狀態

runnable——執行(可執行)狀態

blocked——阻塞狀態

timed_waiting——休眠狀態

waiting——等待狀態

terminated——終止狀態

threadstate類

public class threadstate implements runnable

public synchronized void waitforyears() throws interruptedexception

public synchronized void notifynow() throws interruptedexception

@override

public void run() catch (interruptedexception e) }}

測試類

public class test01 

}

activecount()——返回此執行緒組中活動執行緒的估計數

activegroupcount()——返回此執行緒組中活動執行緒組的估計數

enumerate(thread list,boolean recurse)——把此執行緒組中所有活動執行緒複製到指定陣列中

enumerate(threadgroup list,boolean recurse)——把對此執行緒中的所有活動子組的引用複製到指定陣列中

getname()——返回此執行緒組的名稱

getparent()——返回此執行緒組的父執行緒組

/**

* 獲得根執行緒組

* @return

*/private static threadgroup getrootthreadgroups()else

}//返回根執行緒組

return rootgroup;

}/**

* 獲得給定執行緒組中所有執行緒名

* @param group

* @return

*/public static listgetthreads(threadgroup group){

//建立儲存執行緒名的列表

listthreadlist=new arraylist();

//根據活動執行緒數建立執行緒陣列

thread threads=new thread[group.activecount()];

//複製執行緒到執行緒陣列

int count=group.enumerate(threads,false);

//遍歷執行緒陣列將執行緒名及其所在組儲存到列表中

for(int i=0;igetthreadgroups(threadgroup group){

//獲得給定執行緒組中線程名

listthreadlist=getthreads(group);

//建立執行緒組陣列

threadgroup groups=new threadgroup[group.activegroupcount()];

//複製子執行緒組到執行緒組資料

int count=group.enumerate(groups,false);

//遍歷所有子執行緒組

start()——新建、啟動新執行緒

sleep(5)——休眠0.5秒

wait(5)——等待0.5秒

wait()——永久等待

notify()——喚醒由wait()進入等待狀態的執行緒

notifyall()——喚醒等待的所有執行緒

join()——等待呼叫該方法的執行緒終止

join(5)——等待呼叫該方法的執行緒終止的時間最長為0.5秒

多執行緒之知識點

多執行緒的學習 1.都不是原子操作,在多執行緒中值可能被改變 因此在多執行緒環境中對乙個變數進行讀寫時,我們需要有一種方法能夠保證對乙個值的遞增操作是原子操作 即不可打斷性,乙個執行緒在執行原子操作時,其它執行緒必須等待它完成之後才能開始執行該原子操作。這種涉及到硬體的操作會不會很複雜了,幸運的是,...

多執行緒知識點總結

多執行緒的問題主要圍繞3個問題處理 1.原子性,2.可見性,3.有序性 1.原子性,不可被其他執行緒打斷的操作。如read.write sychronized 2.可見性 一條執行緒修改了某值,新值對其他執行緒立即可知 普通變數是通過主記憶體完成多執行緒的共享,因此在多執行緒的情況下,很多髒資料。v...

多執行緒 知識點總結二

1.sleep 和wait 方法的區別?sleep 必須指時間 不釋放鎖。wait 可以不指定時間,也可以指定時間 釋放鎖。2.為什麼wait notify notifyall 等方法都定義在object類中?wait 等待,notify 喚醒單個執行緒,notifyall 喚醒所有的執行緒 這些方...