Java线程sleep()方法

标签 java multithreading sleep

我正在做Java的过去试卷,我对下面列出的一个问题感到困惑:

当线程在其 run() 方法中执行以下语句时会发生什么? (选择所有适用项。)

sleep(500);

一个。它将停止执行,并在恰好 500 毫秒后开始执行。

B.它将停止执行,并在不早于 500 毫秒后再次开始执行。

C.这将导致编译器错误,因为您不能在 run() 方法中调用 sleep(…) 方法。

D.它将导致编译器错误,因为 sleep(…) 方法不接受任何参数。

我选择 A、B。但关键答案只有B,是否存在A也可能发生的情况?谁能帮我澄清一下?非常感谢。

最佳答案

I select A,B. but the key answer is only B, does there exist any circumstances that A could also happen? Could anyone please clarify that for me?

是的,根据您的应用,您肯定可以获得 500 毫秒的 hibernate 时间,而不是多一纳秒。

但是,B 之所以是更好的答案,是因为无法保证任何线程何时会再次运行。您的应用程序可能具有大量 CPU 绑定(bind)线程。即使 sleep 线程现在可以运行,它也可能在很长一段时间内无法获得任何周期。精确的 hibernate 时间还高度依赖于操作系统线程调度器和时钟精度的细节。您的应用程序还可能必须与同一系统上的其他应用程序竞争,这可能会延迟其继续执行。

例如,在我的速度极快的 8xi7 CPU Macbook Pro 上,以下程序显示了 604 毫秒的最大 sleep 时间:

public class MaxSleep {

    public static void main(String[] args) throws Exception {
        final AtomicLong maxSleep = new AtomicLong(0);
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // fork 1000 threads
        for (int i = 0; i < 1000; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        long total = 0;
                        // spin doing something that eats CPU
                        for (int j = 0; j < 10000000; j++) {
                            total += j;
                        }
                        // this IO is the real time sink though
                        System.out.println("total = " + total);
                        try {
                            long before = System.currentTimeMillis();
                            Thread.sleep(500);
                            long diff = System.currentTimeMillis() - before;
                            // update the max value
                            while (true) {
                                long max =  maxSleep.get(); 
                                if (diff <= max) {
                                    break;
                                }
                                if (maxSleep.compareAndSet(max, diff)) {
                                    break;
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        System.out.println("max sleep ms = " + maxSleep);
    }
}

关于Java线程sleep()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501552/

相关文章:

Java Thread.sleep 异常

objective-c - 重复更新 UIImage 未显示在屏幕上

java - 如何从当前运行的 jar 中复制文件

java - @Inject 在 session 中创建一个新的bean实例

python - 使用 asyncio 有两个无限任务

c# - 从任务返回而不阻塞 UI 线程

c - 在不创建新线程的情况下将调试器附加到进程

java - 如何在batchUpdate期间覆盖Spring JDBCTemplate的事务超时值

Java GPA 计算结果问题

ios - 如果设备被锁定,CADislayLink 不会触发