線程生命週期以下:java
驗證代碼以下:編程
public class LifeCycleDemo {
public static void main(String[] args) {
Thread t0 = new Thread(new Runnable() {
public void run() {
Counter.increase();
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
Counter.increase();
}
});
//建立後狀態爲NEW
printState(t0);
printState(t1);
t0.start();
t1.start();
//啓動後狀態爲RUNNABLE
printState(t0);
printState(t1);
sleep(1000);
//運行後t0得到同步鎖,進入代碼塊執行Thread.sleep後狀態變爲TIMED_WAITING,t1等待獲取同步鎖,狀態爲BLOCKED
printState(t0);
printState(t1);
sleep(4000);
//線程執行完後狀態爲TERMINATED
printState(t0);
printState(t1);
System.out.println("count: " + Counter.getCount());
}
private static void printState(Thread t) {
System.out.println(t.getName() + " " + t.getState());
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Counter {
private static int count;
public synchronized static void increase() {
count = count +1;
try {
//模擬併發爭用
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
public static int getCount() {
return count;
}
}
複製代碼
打印日誌:緩存
Thread-0 NEW
Thread-1 NEW
Thread-0 RUNNABLE
Thread-1 RUNNABLE
Thread-0 BLOCKED
Thread-1 TIMED_WAITING
Thread-0 TERMINATED
Thread-1 TERMINATED
count: 2
複製代碼
驗證代碼以下:安全
public class LifeCycleDemo2 {
public static void main(String[] args) {
Thread t0 = new Thread(new ChildThread(Thread.currentThread()));
t0.start();
//子線程啓動後狀態爲RUNNABLE
printState(t0);
try {
//子線程join後,主線程狀態爲WAITING
t0.join();
//主線程狀態爲RUNNABLE
printState(Thread.currentThread());
//子線程運行結束,狀態爲TERMINATED
printState(t0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void printState(Thread t) {
System.out.println(t.getName() + " " + t.getState());
}
}
class ChildThread implements Runnable {
Thread parentThread;
public ChildThread(Thread parentThread) {
this.parentThread = parentThread;
}
public void run() {
try {
Thread.sleep(2000);
//這裏是在子線程join以後打印,此時主線程狀態爲WAITING
System.out.println(parentThread.getName() + " " + parentThread.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
複製代碼
輸出日誌:bash
Thread-0 RUNNABLE
main WAITING
main RUNNABLE
Thread-0 TERMINATED
複製代碼
其餘場景不在單獨列出代碼。併發
end.post
相關閱讀:
Java併發編程(一)知識地圖
Java併發編程(二)原子性
Java併發編程(三)可見性
Java併發編程(四)有序性
Java併發編程(五)建立線程方式概覽
Java併發編程入門(六)synchronized用法
Java併發編程入門(七)輕鬆理解wait和notify以及使用場景
Java併發編程入門(九)死鎖和死鎖定位
Java併發編程入門(十)鎖優化
Java併發編程入門(十一)限流場景和Spring限流器實現
Java併發編程入門(十二)生產者和消費者模式-代碼模板
Java併發編程入門(十三)讀寫鎖和緩存模板
Java併發編程入門(十四)CountDownLatch應用場景
Java併發編程入門(十五)CyclicBarrier應用場景
Java併發編程入門(十六)秒懂線程池差異
Java併發編程入門(十七)一圖掌握線程經常使用類和接口
Java併發編程入門(十八)再論線程安全優化
Java極客站點: javageektour.com/this