根據一些資料整理如下:
一個程序中可以有多條執行線索同時執行,一個線程就是程序中的一條執行線索,每個線程上都關聯有要執行的代碼,即可以有多段程序代碼同時運行,每個程序至少都有一個線程,即main方法執行的那個線程。
狀態:就緒,運行,synchronize阻塞,wait和sleep掛起,結束。wait必須在synchronized內部調用。
調用線程的start方法后線程進入就緒狀態,線程調度系統將就緒狀態的線程轉為運行狀態,遇到synchronized語句時,由運行狀態轉為阻塞,當synchronized獲得鎖后,由阻塞轉為運行,在這種情況可以調用wait方法轉為掛起狀態,當線程關聯的代碼執行完后,線程變為結束狀態。
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內部run方法要用同意對象作為監視器,不能用this,thread1的this和thread2的this不是同一個對象
synchronized (MutiThread.class) {
System.out.println("enter thread1");
System.out.println("thread1 is waiting");
try {
//thread1進入等待,并把自己的鎖讓出,等待別的線程調用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就無法接著進行,該方法并不是立馬讓出鎖,若是之后還有代碼,需要執行完這些代碼后才會釋放鎖
//告訴調用過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");
}
}
}
}
輸出結果
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