TimerTask vs计时器vs线程? [英] TimerTask vs Timer vs Thread?
问题描述
我试图在JLabel上连续显示日期和时间.因此,在我观看的上一教程中,发言人说:您必须在必要时使用此线程,因为它会占用程序的内存."
I'm trying to show Date and time continuously on a JLabel. So on the last tutorial I've watched.the speaker said "You must Use this threads whenever necessary because it takes memory in your program".
所以我搜索了其他替代方法,然后找到了Timer和TimerTask,这是在程序的长期运行中最有效的方法?
So I search other alternatives and i find Timer and TimerTask which is the most efficient way to use on the long run of the program?
推荐答案
计时器用于在一定间隔,延迟或两者结合之后运行任务(即TimerTask).在您的情况下,您可以使用以下方式:
A Timer is used to run a task (i.e: TimerTask) on an interval, after a delay, or a combination of the two. In your case, you can use something like this:
java.util.Timer timer = new java.util.Timer();
timer.schedule(new TimerTask() {
public void run() {
// do task
}
}, 0, 1000); //updates every second
请注意,为了更新Swing线程以外的其他线程中的Swing组件,您需要使用SwingWorker(请参见摇摆计时器.下面的代码使用Swing计时器每秒钟用一个新日期更新标签:
Note that in order to update a Swing component in a thread other than the Swing thread, you'll need to use a SwingWorker (see Swing Concurrency Tutorial), or user a Swing Timer instead. The code below is using a Swing timer to update the label with a new date every second:
javax.swing.Timer timer1 = new javax.swing.Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(new Date());
}
});
timer1.setRepeats(true);
timer1.setDelay(1000);
我尚未对此进行测试,因此您可能需要对其进行一些微调才能为您工作.
I haven't tested this, so you may need to tweak it a little to work for you.
这篇关于TimerTask vs计时器vs线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!