執行緒生命週期及狀態

2021-10-05 15:33:47 字數 2490 閱讀 3898

* 示例2 - 多執行緒執行狀態切換示例

*/public class demo2

});system.out.println("沒呼叫start方法,thread1當前狀態:" + thread1.getstate().tostring());

thread1.start();

thread.sleep(2000l); // 等待thread1執行結束,再看狀態

system.out.println("等待兩秒,再看thread1當前狀態:" + thread1.getstate().tostring());

// thread1.start(); todo 注意,執行緒終止之後,再進行呼叫,會丟擲illegalthreadstateexception異常

system.out.println();

system.out.println("############第二種:新建 -> 執行 -> 等待 -> 執行 -> 終止(sleep方式)###########################");

thread thread2 = new thread(new runnable() catch (interruptedexception e)

system.out.println("thread2當前狀態:" + thread.currentthread().getstate().tostring());

system.out.println("thread2 執行了");

}});

system.out.println("沒呼叫start方法,thread2當前狀態:" + thread2.getstate().tostring());

thread2.start();

system.out.println("呼叫start方法,thread2當前狀態:" + thread2.getstate().tostring());

thread.sleep(200l); // 等待200毫秒,再看狀態

system.out.println("等待200毫秒,再看thread2當前狀態:" + thread2.getstate().tostring());

thread.sleep(3000l); // 再等待3秒,讓thread2執行完畢,再看狀態

system.out.println("等待3秒,再看thread2當前狀態:" + thread2.getstate().tostring());

system.out.println();

system.out.println("############第三種:新建 -> 執行 -> 阻塞 -> 執行 -> 終止###########################");

thread thread3 = new thread(new runnable()

}});

synchronized (demo2.class)

thread.sleep(3000l); // 再等待3秒,讓thread3執行完畢,再看狀態

system.out.println("等待3秒,讓thread3搶到鎖,再看thread3當前狀態:" + thread3.getstate().tostring());

}}#######第一種狀態切換 - 新建 -> 執行 -> 終止################################

沒呼叫start方法,thread1當前狀態:new

thread1當前狀態:runnable

thread1 執行了

等待兩秒,再看thread1當前狀態:terminated

############第二種:新建 -> 執行 -> 等待 -> 執行 -> 終止(sleep方式)###########################

沒呼叫start方法,thread2當前狀態:new

呼叫start方法,thread2當前狀態:runnable

等待200毫秒,再看thread2當前狀態:timed_waiting

thread2當前狀態:runnable

thread2 執行了

等待3秒,再看thread2當前狀態:terminated

############第三種:新建 -> 執行 -> 阻塞 -> 執行 -> 終止###########################

沒呼叫start方法,thread3當前狀態:new

呼叫start方法,thread3當前狀態:runnable

等待200毫秒,再看thread3當前狀態:blocked

thread3當前狀態:runnable

thread3 執行了

等待3秒,讓thread3搶到鎖,再看thread3當前狀態:terminated

process finished with exit code 0

java多執行緒 執行緒狀態及生命週期

1.新建狀態 new 新建立了乙個執行緒物件。2.就緒狀態 runnable 執行緒物件建立後,其他執行緒呼叫了該物件的start 方法。該狀態的執行緒位於可執行執行緒池中,變得可執行,等待獲取cpu的使用權。3.執行狀態 running 就緒狀態的執行緒獲取了cpu的使用權,執行程式 4.阻塞狀態...

執行緒的生命週期狀態

第一步 新建狀態 使用new關鍵字新建執行緒,此時處於新建狀態 第二步 就緒狀態 當呼叫了該執行緒的start 方法,執行緒啟動,處於就緒狀態,但是不一定執行 第三步 執行狀態 需要考作業系統cup的排程執行,如果作業系統是搶占式排程,當執行緒搶占到了cup的執行許可權,執行緒開始執行 如果是分時排...

執行緒的狀態和生命週期

1 新建狀態 create 建立乙個執行緒類的物件後,產生的新執行緒就進入新建狀態。如 thread myth new mythread 2 可執行狀態 runable 也叫就緒狀態,呼叫start 方法後進入。3 執行狀態 running 當處於就緒狀態的執行緒被呼叫並獲得了cpu等執行必須的資源...