1.多執行緒的實現方式
1.繼承thread
public class demo2_thread }}
class mythread extends thread
}}
2.實現runnable介面
public class demo3_runnable }}
class myrunnable implements runnable
}}
2.執行緒相關的api
1.setname:設定執行緒的名字
2.getname:獲取執行緒的名字
3.thread.currentthread().setname():設定當前執行緒的名字
4.thread.currentthread().getname():獲取當前執行緒的名字
5.thread.sleep():休眠執行緒(控制當前執行緒休眠)
6.thread.setdaemon(true):設定守護執行緒(設定乙個執行緒為守護執行緒, 該執行緒不會單獨執行, 當其他非守護執行緒都執行結束後, 自動退出)
7.thread.join():加入程序(當前執行緒暫停, 等待指定的執行緒執行結束後, 當前執行緒再繼續)
8.thread.setpriority() 設定執行緒的優先順序(0到10 預設為5)
3.同步**塊
1.使用synchronized關鍵字加上乙個鎖物件來定義一段**, 這就叫同步**塊
private static void print01()
}; private static void print02()
}
2.使用synchronized關鍵字修飾乙個方法, 該方法中所有的**都是同步的
1.非靜態同步函式的鎖是:this
2. 靜態的同步函式的鎖是:位元組碼物件
public static synchronized void print02()
Java基礎之多執行緒
實現介面runnable 實現介面callable 結合執行緒池 實現callable介面或者runnable介面 呼叫如下方法即可 結束任務 執行緒池方式 初始化執行緒池 executorservice pool executors.newfixedthreadpool 2 可以執行runnabl...
Java之多執行緒
執行緒的狀態 繼承thread類和實現runable介面,新執行緒執行,即是執行run 方法裡的內容 public class testthread extends thread if count 10 0 catch interruptedexception e run方法結束即當前執行緒結束 p...
java之多執行緒
建立乙個執行緒的方法有三種,thread,runnable 實現,實現callable call 作為實體,可以返回try,catch 1.thread t new thread 2.class x implements runable thread t new thread new x 3.cal...