Robot.delay(int)与Thread.sleep(long) [英] Robot.delay(int) versus Thread.sleep(long)
问题描述
我有一个程序,其唯一目的是无限循环驱动 java.awt.Robot
直到满足退出条件。
I have a program whose only purpose is to drive a java.awt.Robot
in an infinite loop until an exit condition is met.
机器人快速连续执行许多动作,这需要在它们之间使用标准的UI延迟。为此,我使用了 java.awt.Robot.setAutoDelay(int ms)
,它似乎正是为此目的而设计的。
The robot performs a number of actions in quick succession, which require a standard UI delay between them. For this, I use java.awt.Robot.setAutoDelay(int ms)
, which appears to be designed for precisely this purpose.
但是,在其他时候,我需要插入任意长的延迟才能完成操作。我似乎可以选择使用 java.awt.Robot.delay(int ms)
或 java.lang.Thread.sleep(long ms)之间进行选择
,很好奇它们之间的区别以及应该使用的区别。
At other times, however, I need to insert arbitrarily long delays for operations to complete. I appear to have a choice between using java.awt.Robot.delay(int ms)
or java.lang.Thread.sleep(long ms)
, and am curious what the differences between them are, and which I should use.
我的直觉是将所有操作保持在相同的地方,并使用 java.awt.Robot.delay(int ms)
。但是,考虑了一会儿之后,我认为 java.awt.Robot.delay(int ms)
会将一个操作放到机器人的操作堆栈上,如果这是我在无限循环中唯一的延迟,我可能会很快且不必要地为机器人生成一个非常大的事件队列。
My gut instinct was to keep all my operations in the same "place", and use java.awt.Robot.delay(int ms)
. However, after thinking about it for a moment, I assumed that java.awt.Robot.delay(int ms)
would put an operation on the Robot's stack of operations to complete, and if those were my only delays in an infinite loop, I may very quickly, and needlessly, generate an absurdly large queue of events for the Robot.
我检查了用于 java.awt.Robot.delay(int ms)
,它告诉我以下内容:
At that point, I checked the API for java.awt.Robot.delay(int ms)
, which told me the following:
睡眠指定的时间。要捕获发生的任何
InterruptedException
,可以代替使用Thread.sleep()
。
由于未能对此事件获得任何有用的见识,我选择问你们。
Having failed to gain any useful insight into the matter, I elected to ask you guys.
推荐答案
首先,我还要假设使用 delay()
会产生大量事件,尤其是在读取 waitForIdle()
的Javadoc之后:
At first I would also assume that using delay()
would generate a large queue of events, in particular after reading the javadoc for waitForIdle()
:
等待直到所有当前事件发生事件队列已处理
Waits until all events currently on the event queue have been processed
但检查 Robot.delay()$ c的源代码$ c>在检查延迟时间为正数且不超过1分钟后,表明它基本上是
Thread.sleep()
!
but checking the source code of Robot.delay()
shows that it basically is a Thread.sleep()
, after checking that the delay time is positive and not more than 1 minute!
摘要:两种解决方案几乎相同,请使用 Thread.sleep()
延迟一分钟以上,或者
Abstract: both solutions are almost the same, use Thread.sleep()
for delaying longer than 1 minute or catching the InterruptedException.
使用Java编程多年后,我发现了如何无需捕获InterruptedException就可以睡觉(不考虑创建机器人的开销)
after years of programming with Java I found how to sleep without having to catch the InterruptedException (disregarding the overhead of creating a Robot)
这篇关于Robot.delay(int)与Thread.sleep(long)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!