0

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

@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();
            }
        }
    }
}

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

4

4 回答 4

1

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

    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();
}
于 2013-02-11T12:50:18.070 回答
0

您在更新 GUI 的线程中调用此方法,并且您正在暂停 GUI 刷新。产生一个新线程并在那里执行。

于 2013-02-11T12:51:26.027 回答
0

无限循环?? while (true) {.....}

你应该如何离开这里 - 在循环中添加一个打印语句,你会知道你在按钮点击后被困在这里

于 2013-02-11T12:54:39.717 回答
0

好,我知道了。这是我应该做的:

@Override
public void actionPerformed(ActionEvent action) {
    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();
    }
}
于 2013-02-11T15:02:44.320 回答