我可以使用Timer对象使程序饱和吗? [英] Can I saturate a program with Timer objects?

查看:80
本文介绍了我可以使用Timer对象使程序饱和吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计划使用许多Timer对象的程序,据我了解,每个Timer均在其自己的线程上运行.所以我想知道是否有可能启动太多的计时器,以至于过多的线程会损害程序的性能.

I have a program for which I plan to use a lot of Timer objects, and as I understand it each Timer runs on it's own thread. So I wondered if it's possible to start so many Timers that it hurts the performance of the program with too many threads.

例如,我正在考虑使用几对(布尔值,计时器)使布尔值在几个不同的时间间隔内反转.

For example, I was thinking of having several (boolean, Timer) pairs to have booleans that invert at several different time intervals.

推荐答案

是的,Timer对象确实消耗线程资源,因此有可能在JVM中达到极限.如果您的目标是安排任务在不同的时间点运行,则可能需要查看许多Java 执行器类提供了一个方便的工厂用于生成这些对象.一些实现利用线程池,您可以配置线程池以确定可以同时运行多少个任务.您还可以使用任务产生的输出(如果有),并在程序需要退出时以有序的方式关闭任务.

Yes, Timer objects do consume thread resources, so it is possible to hit a limit within the JVM. If your goal is to schedule tasks to run at various points in time, you might want to look at one of the many Java ExecutorService implementations such as ScheduledThreadPoolExecutor. The Executors class provides a convenient factory for generating these objects. Several implementations utilize thread pools, which you can configure to determine how many tasks may run simultaneously. You can also consume output that the tasks produce (if any) and shutdown the tasks in an orderly fashion if your program needs to exit.

这篇关于我可以使用Timer对象使程序饱和吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆