主方法完成后摆动计时器持久性 [英] Swing timer persistence after main method finishes

查看:25
本文介绍了主方法完成后摆动计时器持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序来执行一个简单的任务并每 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 计时器来实现这一点,因为我相信这是最好的方法.问题是我不确定在 main 方法执行完毕后如何让程序继续运行.例如,我有:

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(..),但这感觉就像一个拙劣的工作,并且最终的持续时间是有限的.我也可以做 while(true),但我认为这是不好的做法.

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.

谢谢.

推荐答案

只要 EDT 处于活动状态,Swing Timer 就会保持活动状态,通常这是通过使 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).

这篇关于主方法完成后摆动计时器持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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