我正在使用一个按钮在我的应用程序中启动后台服务。这是我正在使用的代码:

@Override
public void actionPerformed(ActionEvent action) {
    if (action.getActionCommand().equals("Start")) {
        while (true) {
            new Thread(new Runnable() {
                public void run() {
                    System.out.println("Started");
                }
            }).start();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


这确实每秒更新一次服务,这正是我想要的。问题是它冻结了其余的应用程序。我如何实现它以免发生这种情况?

最佳答案

以下可能导致您的应用程序暂停:

    while (true) {
        ...
    }


尝试删除这些行。

编辑:根据注释,要使新启动的线程每秒触发一次,请在run()方法内移动sleep和while循环:

if (action.getActionCommand().equals("Start")) {
    new Thread(new Runnable() {
        public void run() {
            while (true) {
                System.out.println("Started");        }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
       }
   }).start();
}

08-04 17:02