在java中每2秒重复一次动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25296718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Repeat an action every 2 seconds in java
提问by user3850946
I have to repeat a part of my code every 2 seconds how could I do that? don't tell me to use
try {
Thread.sleep(millisecondi);
}
catch (Exception e) {}
我必须每 2 秒重复我的一部分代码,我该怎么做?不要告诉我使用
try {
Thread.sleep(millisecondi);
}
catch (Exception e) {}
because freeze the application
因为冻结应用程序
回答by Christoffer
If your application is to stay responsive you need to do this in another thread. Or you could simply create a timerand scheduleit.
如果您的应用程序要保持响应,您需要在另一个线程中执行此操作。或者您可以简单地创建一个计时器并安排它。
Whatever thread you're in when you tell it to sleep - will impeccably do so...
当你告诉它睡觉时,无论你处于什么线程 - 都会无可挑剔地这样做......
Something like this:
像这样的东西:
Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
@Override
public void run() {
// whatever you need to do every 2 seconds
}
};
timer.schedule(myTask, 2000, 2000);