1)?線程的狀態(tài)轉(zhuǎn)換
???新建(New Thread):創(chuàng)建后尚未啟動(dòng)
???就緒狀態(tài)(Runnable):線程已經(jīng)被啟動(dòng)抹蚀,正在等待分配時(shí)間片,一旦得到時(shí)間片就開始運(yùn)行
???運(yùn)行狀態(tài)(Running):線程已經(jīng)獲得資源正在運(yùn)行
???阻塞狀態(tài)(Bloked):此時(shí)線程仍然活著
???死亡(Dead):此時(shí)線程已死亡府树,有可能是線程執(zhí)行完畢,也有可能是被殺死的
2)?創(chuàng)建線程的方法
2.1)? 定義一個(gè)線程類,實(shí)現(xiàn)Runnable接口肛冶,實(shí)現(xiàn)run()方法
public class MyThread implements Runnable{
@Override
public void run() {
}
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t = new Thread();
t.start();
}
}
2.2)? 繼承Thread類鲜锚,重寫run()方法
public class MyThread extends Thread{
public void run () {
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
}
2.3)? 定義一個(gè)線程類突诬,實(shí)現(xiàn)Callable接口苫拍,實(shí)現(xiàn)call()方法,與實(shí)現(xiàn)Runnable接口不同的地方在于該方法有返回值,并且返回值通過FutureTask封裝
public class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 1;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread mt = new MyThread();
FutureTask<Integer> ft = new FutureTask<>(mt);
Thread t = new Thread(ft);
t.start();
System.out.println(ft.get());
}
}
總結(jié):雖然上述三種方式都能達(dá)到創(chuàng)建線程的目的,但是實(shí)現(xiàn)接口會(huì)更好一些旺隙,因?yàn)镴ava中不支持多繼承绒极,但是可以多實(shí)現(xiàn),且繼承Thread開銷大催束。
3)?線程控制基本方法
???isAlive():是否活著集峦,即判斷線程是否終止
???Thread.sleep():將當(dāng)前線程指定一個(gè)毫秒數(shù)
???join():調(diào)用某線程的該方法,將當(dāng)前線程與該線程“合并”抠刺,但是是等你執(zhí)行完我再執(zhí)行
???yield():讓出CPU給其他線程塔淤,就讓一下,當(dāng)前線程進(jìn)入就緒隊(duì)列
???wait():當(dāng)前線程進(jìn)入對象的wait pool
???notify()/notifyAll():喚醒對象的wait pool中的一個(gè)/所有等待線程
???getPriority():獲得線程優(yōu)先級(jí)數(shù)值速妖,優(yōu)先級(jí)越高的線程獲得CPU執(zhí)行時(shí)間越多
???setPriority():設(shè)置線程優(yōu)先級(jí)數(shù)值高蜂,優(yōu)先級(jí)越高的線程獲得CPU執(zhí)行時(shí)間越多
???如何停止一個(gè)線程?不是調(diào)用stop()方法罕容,這種方法很粗暴备恤,就好比有人正在熟睡你用棒子把他打醒,可以在主線程中使用shutDown()方法
4)?線程同步
???多個(gè)線程訪問同一個(gè)資源锦秒,這些線程之間協(xié)調(diào)的問題叫同步
???比如去衛(wèi)生間如廁露泊,2個(gè)人不能同時(shí)在一個(gè)坑位,這個(gè)時(shí)候你可以選擇把門鎖上旅择,這樣別人就進(jìn)不來了惭笑,就是我在訪問這個(gè)資源的時(shí)候其他人誰也別想動(dòng),即鎖機(jī)制生真,synchronized沉噩,它可以同步一個(gè)方法,類柱蟀,代碼塊以及靜態(tài)方法川蒙。
???同步一個(gè)方法:
public class TestSynchronized {
public synchronized void a() {
}
}
???同步一個(gè)類:
public class TestSynchronized {
public void a() {
synchronized (TestSynchronized.class) {
}
}
}
???同步一個(gè)代碼塊:
public class TestSynchronized {
public void a() {
synchronized (this) {
}
}
}
???同步一個(gè)靜態(tài)方法:
public class TestSynchronized {
public synchronized static void a() {
}
}