繁体   English   中英

使用 thread.sleep() 进行轮询如何工作?

[英]How does polling with thread.sleep() work?

我是 Java 线程的新手,我试图了解它们是如何工作的; 考虑以下代码:

public class ZooInfo {
private static int counter = 0;

public static void main(String args[]) throws InterruptedException {    

    new Thread(() -> {
        for(int i=0; i<500; i++) ZooInfo.counter++;
        }).start();
    
    while(ZooInfo.counter<100) {
        System.out.println("Not reached yet");
    Thread.sleep(1000);
    }
    
    System.out.println("Reached!");
}   
}

上面代码的输出:

Not reached yet
Reached!

我不明白为什么输出只打印一次“尚未到达”,而不是每次计数器小于 100 时。我期望输出打印“尚未到达”100,然后打印“已到达”?

我不明白为什么输出只打印一次“尚未到达”,而不是每次计数器小于 100 时。 “ - 确实如此! 但是, ZooInfo.counter的值ZooInfo.counter只检查一次。 线程已启动( new Thread(() -> { for(int i=0; i<500; i++) ZooInfo.counter++; }).start();在前 100 次迭代中将花费不到一秒的时间。删除Thread.sleep(...)不一定会改变行为(对我来说,它导致Not yet reached!被打印结束 1-3 次)。这是因为新创建的线程仍然领先. 此外,两个线程不会“一致”运行,即一个线程可能比另一个线程执行得更快或更慢。

此外,正如@Amongalen@Polygnome指出的那样,打印到System.out很慢。 我们可以通过使用StringBuilder来改进这一点:

final String lineSeparator = System.lineSeparator();
new Thread(() -> {
    for (int i = 0; i < 500; i++) ZooInfo.counter++;
}).start();

final StringBuilder builder = new StringBuilder();
while (ZooInfo.counter < 100) {
    builder.append("Not reached yet").append(lineSeparator);
}

builder.append("Reached!");
System.out.println(builder.toString());

这将增加次数Not reached yet! 被打印。

Ideone 演示


备注:字段private static int counter = 0; 还应该声明为volatile以保证线程之间的正确可见性。

暂无
暂无

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

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