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時間片