我还是Java的初学者,所以我对线程和并发还没有了解太多。但是,我希望能够使用 ScheduledThreadPoolExecutor 作为计时器,因为我在使用 java.util.Timer 和 TimerTask 时遇到问题。我对线程的创建非常感兴趣,并且知道我将在几周内学习它们。但是,如果可能的话,有人可以给我一个基本示例,说明如何将我当前使用 util.timer 的小型测试程序转换为使用 ScheduledThreadPoolExecutor 吗?
我想尽快完成这个示例,所以我没有太多时间来学习线程 - 无论我多么想。话虽如此,请包括您认为 Java 初学者应该了解的有关 ScheduledThreadPoolExecutor 的重要内容。
示例程序
我做了一个快速的小例子来代表我在更大的程序中遇到的问题。该程序应该做的是允许用户按下按钮来启动计数器。然后,用户必须能够在他/她想要的时候停止和重新启动计数器。在较大的程序中,该计数器保持相等至关重要,因此我使用了
调度AtFixRate()
方法。同样重要的是初始延迟始终相同(在本例中为 0)。
问题(我相信您会看到)是,一旦计时器被取消,它就无法重新启动 - 我希望 ScheduledThreadPoolExecutor 能够解决这个问题。
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;
import java.util.Timer;
public class Tester extends JFrame {
JButton push = new JButton("Push");
static JTextArea textOut = new JTextArea();
Timer timer = new Timer();
boolean pushed = false;
static int i = 1;
public Tester() {
super();
add(push, BorderLayout.NORTH);
add(textOut);
push.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!pushed) {
timer.scheduleAtFixedRate(new Task(), 0, 1000);
pushed = true;
} else {
timer.cancel();
pushed = false;
}
}
});
}
static class Task extends TimerTask {
public void run() {
textOut.setText("" + i++);
}
}
public static void main(String[] args) {
Tester a = new Tester();
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.pack();
a.setVisible(true);
}
}
我经常使用这个类进行测试,因此可能会有额外的代码(我想我将其全部删除)。
Replace
Timer timer = new Timer();
with
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
and
class Task extends TimerTask
with
class Task implements Runnable
and
timer.scheduleAtFixedRate(new Task(), 0, 1000);
with
service.scheduleAtFixedRate(new Task(), 0, 1000, TimeUnit.MILLISECONDS);
顺便说一句,您不应该尝试在另一个线程上更新 GUI。相反,您必须将任务添加到 Swing GUI 线程才能执行该任务
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
textOut.setText("" + i++);
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)