Java線程狀態(tài)變換過程代碼解析
更新時間:2020年06月03日 10:16:53 作者:Kuris101
這篇文章主要介紹了Java線程狀態(tài)變換過程代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
線程狀態(tài)
- NEW:剛創(chuàng)建未啟動的線程
- RUNNABLE:正在執(zhí)行狀態(tài)
- BLOCKED:處于阻塞狀態(tài)的線程
- WAITING:正在等待另一個線程執(zhí)行特定動作的線程
- TIMED_WAITING:等待另一個線程執(zhí)行時間到達指定時間
- TERMINATED:線程退出執(zhí)行
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("http://///");
});
//觀察線程狀態(tài)
Thread.State state = thread.getState();
System.out.println(state); //New狀態(tài)
thread.start();
state = thread.getState();
System.out.println(state);//Run狀態(tài)
while (state!=Thread.State.TERMINATED){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();//更新線程狀態(tài)
System.out.println(state);//輸出狀態(tài)
}
}
}
線程禮讓
- 當前正在執(zhí)行的線程暫停,但是不會阻塞
- 當前線程失去處理機,編程就緒狀態(tài)
- 禮讓是否成功取決于CPU,如果禮讓成功,則等待下一次調(diào)度
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"線程開始執(zhí)行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"線程停止執(zhí)行");
}
}
執(zhí)行結(jié)果:

線程強制執(zhí)行到結(jié)束
- 使用join()方法
- 使用join()方法的線程會強制執(zhí)行直到結(jié)束,不會讓出處理機
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("強制執(zhí)行線程來了"+i);
}
}
public static void main(String[] args) throws Exception{
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 500; i++) {
if(i==200){
thread.join();
}
System.out.println("主線程"+i);
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
深層剖析java應(yīng)用開發(fā)中MyBayis緩存
這篇文章主要為大家深層剖析java開發(fā)中MyBayis緩存,文中講解了Mybatis緩存的分類以及使用的方式,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
解讀controller層,service層,mapper層,entity層的作用與聯(lián)系
這篇文章主要介紹了關(guān)于controller層,service層,mapper層,entity層的作用與聯(lián)系,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
spring boot devtools在Idea中實現(xiàn)熱部署方法
這篇文章主要介紹了spring boot devtools在Idea中實現(xiàn)熱部署方法及注意要點,需要的朋友可以參考下2018-02-02

