當(dāng)前位置:
首頁(yè) >
线程休眠
發(fā)布時(shí)間:2024/8/23
43
豆豆
package com.ajax;
//線程休眠:該方法可以讓當(dāng)前正在執(zhí)行的線程暫停一段時(shí)間,進(jìn)入休眠等待狀態(tài)讓其他線程可以執(zhí)行
public class Example04 {public static void main(String[] args) throws Exception{new Thread(new SleepThread()).start();for(int i=1;i<=10;i++){if(i==5){Thread.sleep(2000);//當(dāng)前線程休眠2秒}System.out.println("主線程正在輸出:"+i);Thread.sleep(500);}}
}
class SleepThread implements Runnable{public void run(){for(int i=0;i<=10;i++){if(i==3){try{Thread.sleep(2000);}catch(InterruptedException e){e.printStackTrace();}}System.out.println("線程一正在輸出:"+i);try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();}}}
}
/*運(yùn)行結(jié)果:
主線程正在輸出:1
線程一正在輸出:0
主線程正在輸出:2
線程一正在輸出:1
線程一正在輸出:2
主線程正在輸出:3
主線程正在輸出:4
線程一正在輸出:3
主線程正在輸出:5
線程一正在輸出:4
主線程正在輸出:6
線程一正在輸出:5
主線程正在輸出:7
線程一正在輸出:6
主線程正在輸出:8
線程一正在輸出:7
主線程正在輸出:9
線程一正在輸出:8
主線程正在輸出:10
線程一正在輸出:9
線程一正在輸出:10
解釋:運(yùn)行結(jié)果可以看出當(dāng)i=3的時(shí)候,線程一沒有交替輸出3,而是主線程接著輸出,只有當(dāng)線程休眠完了之后,兩個(gè)線程菜會(huì)恢復(fù)交替執(zhí)行*/
總結(jié)
- 上一篇: 分布式系统的工程化开发方法
- 下一篇: 数据结构实验之排序一:一趟快排