根據(jù)一些資料整理如下:
一個程序中可以有多條執(zhí)行線索同時執(zhí)行,一個線程就是程序中的一條執(zhí)行線索,每個線程上都關(guān)聯(lián)有要執(zhí)行的代碼,即可以有多段程序代碼同時運行,每個程序至少都有一個線程,即main方法執(zhí)行的那個線程。
狀態(tài):就緒,運行,synchronize阻塞,wait和sleep掛起,結(jié)束。wait必須在synchronized內(nèi)部調(diào)用。
調(diào)用線程的start方法后線程進入就緒狀態(tài),線程調(diào)度系統(tǒng)將就緒狀態(tài)的線程轉(zhuǎn)為運行狀態(tài),遇到synchronized語句時,由運行狀態(tài)轉(zhuǎn)為阻塞,當synchronized獲得鎖后,由阻塞轉(zhuǎn)為運行,在這種情況可以調(diào)用wait方法轉(zhuǎn)為掛起狀態(tài),當線程關(guān)聯(lián)的代碼執(zhí)行完后,線程變?yōu)榻Y(jié)束狀態(tài)。
package thread;
public class MutiThread {
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(100);//讓thread1休眠
} catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable{
@Override
public void run() {
//這里的thread1和thread2內(nèi)部run方法要用同意對象作為監(jiān)視器,不能用this,thread1的this和thread2的this不是同一個對象
synchronized (MutiThread.class) {
System.out.println("enter thread1");
System.out.println("thread1 is waiting");
try {
//thread1進入等待,并把自己的鎖讓出,等待別的線程調(diào)用notify方法
MutiThread.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is going on");
System.out.println("thread1 is being over");
}
}
}
private static class Thread2 implements Runnable{
@Override
public void run() {
synchronized(MutiThread.class){
System.out.println("enter thread2");
System.out.println("thread2 notify other thread");
//如果不喚醒,thread1就無法接著進行,該方法并不是立馬讓出鎖,若是之后還有代碼,需要執(zhí)行完這些代碼后才會釋放鎖
//告訴調(diào)用過wait方法的線程可以去參與獲得鎖的競爭
MutiThread.class.notify();
System.out.println("thread2 is sleeping");
try {
Thread.sleep(100);//sleep并沒有讓出鎖,所以thread2接著進行,之后才輪到thread1,只是主動讓出CPU
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going on");
System.out.println("thread2 is being over");
}
}
}
}
輸出結(jié)果
enter thread1
thread1 is waiting
enter thread2
thread2 notify other thread
thread2 is sleeping
thread2 is going on
thread2 is being over
thread1 is going on
thread1 is being over