main 方法完成后 Swing 计时器持续存在
我正在尝试创建一个程序来执行简单的任务并每x
秒生成一个输出。我还希望该程序一直运行,直到我决定手动关闭该程序。
我一直在尝试使用 Swing 计时器来实现这一点,因为我相信这是最好的方法。问题是我不确定主方法执行完毕后如何让程序继续运行。例如我有:
static ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static void main(String[] args) throws Exception{
Timer timer = new Timer(3000, taskPerformer);
timer.start();
}
它立即完成执行。我可以通过将当前执行线程置于睡眠状态Thread.currentThread().sleep(..)
来避免这个问题,但这感觉像是一个糟糕的工作,并且最终的持续时间是有限的。我也可以这样做 while(true),但我认为这是不好的做法。
我的问题是如何获得所需的持久性行为,以及是否有比使用 Swing 计时器更好的方法。
谢谢。
I am trying to create a program to perform a simple task and produce an output every x
seconds. I also want the program to run until I decide to manually close the program.
I have been attempting to implement this using a Swing timer, as I believe this is the best way. The problem is I'm not sure how to keep the program going once the main method has finished executing. So for example I have:
static ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static void main(String[] args) throws Exception{
Timer timer = new Timer(3000, taskPerformer);
timer.start();
}
which just finishes execution immediately. I can dodge the problem by putting the current thread of execution to sleep Thread.currentThread().sleep(..)
, but this feels like a botch job, and will be ultimately be finite in duration. I can also do while(true), but I believe this is bad practice.
My question is how to get the desired persistence behavior, and if there is a better way than using Swing timers.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要 EDT 处于活动状态,Swing 计时器就会保持活动状态,通常这是通过使 Swing GUI 存在且可见来完成的(这会创建一个非守护线程,该线程将持续存在,直到 GUI 退出)。如果您不需要 Swing GUI,则不要使用 Swing 计时器。也许可以使用 java.util.Timer,并且在您发出命令之前不要退出 main 方法(无论您打算这样做)。
A Swing Timer will stay alive as long as the EDT is alive, usually this is done by having a Swing GUI present and visible (this creates a non-daemon thread that persists until the GUI exits). If you don't need a Swing GUI, then don't use a Swing Timer. Perhaps instead use a java.util.Timer, and don't exit the main method til you give the word (however you plan to do that).
请改用 java.util.Timer 。关联的线程不会作为守护进程运行。
Use java.util.Timer instead. The associated thread will not run as a daemon.