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时间片



原文地址:https://www.cnblogs.com/yinbiao/p/10179563.html