简体   繁体   English

执行顺序和Thread.sleep

[英]Order of execution and Thread.sleep

Recently I've seen some code which depends on order of execution in different threads which was achieved by calling Thread.sleep with some values. 最近我看到一些代码依赖于不同线程中的执行顺序,这是通过调用Thread.sleep来实现的。 It worked without any problems but I'm sure that in some rare cases it would not. 它没有任何问题,但我确信在某些罕见的情况下它不会。 I wrote some code where order of output depends on how precisely Thread.sleep works. 我写了一些代码,其中输出顺序取决于Thread.sleep精确程度。

public class Test {
    public static Thread createDelayedPrintThread(final String text,
            final long delay) {
        return new Thread() {
            public void run() {
                try {
                    Thread.sleep(delay);
                    System.out.print(text);
                } catch (InterruptedException e) {
                }
            }
        };
    }

    public static void main(String[] args) {
        Thread t1 = createDelayedPrintThread("t1", 10);
        Thread t2 = createDelayedPrintThread("t2", 10);
        t1.start();
        t2.start();
    }
}

This code obliviously can output booth t1t2 and t2t1 so I made delays different: 这段代码t2t1可以输出booth t1t2t2t1所以我的延迟不同:

Thread t1 = createDelayedPrintThread("t1", 10);
Thread t2 = createDelayedPrintThread("t2", 20);

Now it outputs t1t2 but I still sometimes get t2t1 . 现在它输出t1t2但我仍然有时得到t2t1 It usually happens when I do some CPU/IO intensive operations. 它通常发生在我进行一些CPU / IO密集型操作时。
If I change delays to extremely big values 如果我将延迟更改为非常大的值

Thread t1 = createDelayedPrintThread("t1", 1_000); // one second
Thread t2 = createDelayedPrintThread("t2", 60_000); // one minute

would be there any guarantees that the application will output t1t2 ? 将有任何保证应用程序将输出t1t2

Thread.sleep is not guarantees. Thread.sleep不是保证。 Java tutorial, about Thread.sleep(): 关于Thread.sleep()的Java教程:

"However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified." “然而,这些睡眠时间并不能保证精确,因为它们受到底层操作系统提供的设施的限制。此外,睡眠时间可以通过中断终止,我们将在后面的章节中看到。无论如何。 ,你不能假设调用sleep会在指定的时间段内暂停线程。“

So, you need add other multithreading logic for guarantees execution order. 因此,您需要添加其他多线程逻辑以保证执行顺序。

First, your understanding is correct; 首先,你的理解是正确的; no amount of Thread.sleep() (and by the way, since Java 5 you should really be using TimeUnit instead, as in TimeUnit.SECONDS.sleep(2L) ) will guarantee in-order execution; 没有任何Thread.sleep() (顺便说一句,因为Java 5你真的应该使用TimeUnit ,就像在TimeUnit.SECONDS.sleep(2L) )将保证按顺序执行; you cannot guarantee when the OS will schedule this or that thread. 您无法保证操作系统何时安排此线程或该线程。

would be there any guarantees that the application will output t1t2? 将有任何保证应用程序将输出t1t2?

Yes. 是。

For instance, a volatile boolean variable shared by those two threads will do (although you'll need to busy wait so this is not ideal). 例如,这两个线程共享的一个易失性布尔变量就可以了(虽然你需要忙等待,所以这并不理想)。 Another example is a Semaphore . 另一个例子是Semaphore

Solutions are many, and what you will end up with depends entirely upon your requirements. 解决方案很多,您最终将完全取决于您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM