主方法完成后的Swing计时器持久性 [英] Swing timer persistence after main method finishes
问题描述
我正在尝试创建一个程序来执行一个简单的任务,并在每个 x
秒时产生一个输出。我还希望程序运行直到我决定手动关闭程序。
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.
我一直在尝试使用Swing计时器来实现它,因为我相信这是最好的办法。问题是我不确定一旦主方法执行完毕后如何保持程序运行。例如,我有:
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();
}
刚刚立即执行。我可以通过将当前执行线程置于睡眠状态 Thread.currentThread()。sleep(..)
来避免问题,但这感觉就像一个拙劣的工作,并且将会最终持续时间有限。我也可以做(真的),但我相信这是不好的做法。
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.
我的问题是如何获得所需的持久性行为,如果有更好的方法比使用Swing计时器。
My question is how to get the desired persistence behavior, and if there is a better way than using Swing timers.
谢谢。
推荐答案
一个Swing计时器只要EDT处于活动状态,它就会保持活着状态,通常这是通过让Swing GUI存在并且可见(这会创建一个非守护程序线程,直到GUI退出)。如果您不需要Swing GUI,则不要使用Swing Timer。也许改为使用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).
这篇关于主方法完成后的Swing计时器持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!