Thread.sleep() 的精确替代方案

问题描述

我需要一种方法将线程延迟精确的毫秒数(一个乐谱播放应用程序)。我知道 Thread.sleep() 的精度不是很好,所以我决定改为使用 scheduledexecutorservice。我这样做的方式如下:

... //some code
int duration = 100; //delay for 100ms
CountDownLatch l = new CountDownLatch(1);
Executors.newScheduledThreadPool(1).schedule(l::countDown,duration,TimeUnit.MILLISECONDS);
l.await();
... //continue execution

这是一个方法吗?我最担心的是 CountDownLatch,以及它可能增加的任何延迟(如果有)。

谢谢。

解决方法

因此,由于一些问题,您的解决方案并不好。您正在失去使用预定执行器服务所获得的优势,因为使用 await await 将使当前线程进入睡眠状态,然后操作系统将需要在它启动之前再次对其进行调度。

我使用三种不同的技术制作了一个示例。旋转等待,使用 thread.sleep 并使用您的计划执行器想法。旋转等待是最准确的,在 7002 毫秒,而其他两个解决方案在完成时超过 8300 毫秒。

import java.util.concurrent.*;

public class DwellTimes{

    static public void spinWait(long ms){
        long end = System.nanoTime() + ms*1000000;
        long current = System.nanoTime();
        while( current < end){
            current = System.nanoTime();
        }
    }
    
    static public void sleepWait(long ms){
        try{
            Thread.sleep(ms);
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    
    static ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
     
    static public void scheduleWait(long ms){
        try{
            CountDownLatch l = new CountDownLatch(1);
            ses.schedule(l::countDown,ms,TimeUnit.MILLISECONDS);
            l.await();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    
   
    
    public static void main(String[] args){
        long start = System.currentTimeMillis();
        for(int i = 0; i<1000; i++){
            scheduleWait(7);
        }
        long end = System.currentTimeMillis() - start;
        System.out.println( end + "ms elapsed");
    }
}

对于睡眠/等待风格的流程,自旋等待将是最准确的,因为它不会释放线程。它只会继续火爆。

您的调度执行程序示例的问题在于您实际上并未使用调度。您想安排您的任务。

public static void scheduleWork(){
    CountDownLatch latch = new CountDownLatch(1000);
    ses.scheduleAtFixedRate(latch::countDown,7,TimeUnit.MILLISECONDS);
    try{
        latch.await();
    } catch(Exception e){
        throw new RuntimeException(e);
    }
}

最后一个示例可能是管理一致计时的最佳方式,因为您不会继续累积错误。例如,如果您的操作需要几毫秒,则下一个操作不会被延迟除非这几毫秒超过了时间