简体   繁体   English

javax.swing.Timer与java.util.Timer

[英]javax.swing.Timer vs java.util.Timer

I heard all javax.swing classes should only be used if Iam actually building a Swing GUI . 我听说只有在Iam实际构建Swing GUI才能使用所有javax.swing类。 I would like to use javax.swing.Timer without GUI in order to create timer loop. 我想在没有GUI情况下使用javax.swing.Timer来创建定时器循环。 Does it mean that without GUI shall i use java.util.Timer ? 这是否意味着没有GUI我应该使用java.util.Timer

Is it big error to use javax.swing.Timer without GUI ? 没有GUI使用javax.swing.Timer是大错误吗? Can it cause some performance error or slowdown? 它会导致一些性能错误或减速吗?

What are some approaches to creating a loop that will run passively or without halting the main thread? 有什么方法可以创建一个被动运行或不停止主线程的循环?

Thanks in Advance! 提前致谢!

Is it big error to use javax.swing.Timer without GUI ? 没有GUI使用javax.swing.Timer是大错误吗? Can it cause some performance error or slowdown? 它会导致一些性能错误或减速吗?

No, It is not a big error. 不,这不是一个大错误。 But , the ActionEvents associated with the javax.swing.Timer won't fire if there is no non-daemon thread running in the application . 但是,如果应用程序中没有运行non-daemon线程,则不会触发与javax.swing.Timer关联的ActionEvents If no non-daemon thread is running in application then the program will exit gracefully without making the javax.swing.Timer to execute associated actionPerformed method. 如果应用程序中没有运行non-daemon线程,则程序将正常退出而不使javax.swing.Timer执行关联的actionPerformed方法。 But GUI causes the JVM to hang up and let the Timer to execute the actionPerformed method. 但GUI会导致JVM挂起并让Timer执行actionPerformed方法。
In case you are not using GUI, make sure that there is some non-daemon thread running in application. 如果您不使用GUI,请确保在应用non-daemon运行了一些non-daemon线程。

What are some approaches to creating a loop that will run passively or without halting the main thread? 有什么方法可以创建一个被动运行或不停止主线程的循环?

You can use java.util.Timer for this purpose. 您可以使用java.util.Timer来实现此目的。 But now java.util.concurrent has provided a lot of enrich set of APIs to perform concurrent tasks. 但是现在java.util.concurrent提供了许多丰富的API来执行并发任务。 So , now you should move on to ScheduledExecutorService API for this purpose. 因此,现在您应该为此目的转到ScheduledExecutorService API。

Yes it is not recommended since it is another dependency you need. 是的,不推荐它,因为它是您需要的另一个依赖项。

You should try to have as few as possible dependencies. 您应该尝试尽可能少的依赖项。 If java.util.Timer is something that satisfies your needs you definitely should choose this one. 如果java.util.Timer满足您的需求,您一定要选择这个。

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

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