1. 程式人生 > >java中sleep()方法的解析

java中sleep()方法的解析

Thread.sleep(3000);

就是指讓當前正在執行的佔用cpu時間片的執行緒掛起3000ms,把cpu的時間片交給其他執行緒,但是並沒有指定把CPU的時間片接下來到底交給哪個執行緒,而是讓這些執行緒自己去競爭(一般作業系統會根據優先順序排程)

所以說讓當執行緒睡眠,是幫助所有執行緒獲得執行時間的最佳方法

需要的注意的是就算執行緒的睡眠時間到了,他也不是立即會被執行,只是從睡眠狀態變為了可執行狀態,是不會由睡眠狀態直接變為執行狀態的

下面舉一個例子

烏龜和兔子賽跑:Call.java

package 多執行緒;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.omg.CORBA.INTERNAL; /** * @author:yb * @version 建立時間:2018-12-25 下午8:07:11 類說明 */ public class Call { /* * 使用Callable創造執行緒
*/ public static void main(String[] args) throws InterruptedException, ExecutionException { // 建立執行緒池 ExecutorService service = Executors.newFixedThreadPool(2); Race tortoise = new Race("烏龜",1000); Race rabbit = new Race("兔子", 500); Future<Integer> result1 = service.submit(tortoise); Future
<Integer> result2 = service.submit(rabbit); Thread.sleep(3000);//主執行緒掛起3000ms 烏龜和兔子執行緒開始競爭cpu 即烏龜和兔子開始跑,跑的時間都是3000ms tortoise.setFlag(false); rabbit.setFlag(false); //獲取值 int num1=result1.get(); System.out.println("烏龜跑了"+num1+"步"); int num2=result2.get(); System.out.println("兔子跑了"+num2+"步"); //停止服務 service.shutdownNow(); } } class Race implements Callable<Integer>{ private String name;//名稱 private int time;//延時 private int step=0;//步數 public Race(String name,int time) { super(); this.name=name; this.time=time; } private boolean flag= true; public int getTime() { return time; } public void setTime(int time) { this.time = time; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public int getStep() { return step; } public void setStep(int step) { this.step = step; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer call() throws Exception{ while(flag) { Thread.sleep(time); step++; } return step; } }


分析:

main函式也是一個執行緒,執行main函式的時候,Thread.sleep(3000);就是讓main函式執行緒掛起3000ms,所以這個3000ms是烏龜和兔子的比賽總時間,main函式執行緒掛起之後,時間片交給了烏龜和兔子執行緒讓我們去競爭佔用cpu時間片