简体   繁体   中英

javax.swing.Timer vs java.util.Timer

I heard all javax.swing classes should only be used if Iam actually building a Swing GUI . I would like to use javax.swing.Timer without GUI in order to create timer loop. Does it mean that without GUI shall i use java.util.Timer ?

Is it big error to use javax.swing.Timer without GUI ? 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 ? 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 . 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. But GUI causes the JVM to hang up and let the Timer to execute the actionPerformed method.
In case you are not using GUI, make sure that there is some non-daemon thread running in application.

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. But now java.util.concurrent has provided a lot of enrich set of APIs to perform concurrent tasks. So , now you should move on to ScheduledExecutorService API for this purpose.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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