util Timer和swing Timer比对

swing Timer
package timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
* swing timer 通过addActionListener()来增加一个任务<br>
* 可以通过设置delay来动态控制执行频率。<br>
* swing timer 强调执行的顺序,按addActionListener()的倒序执行
* @author Administrator
*
*/
public class SwingTimer extends javax.swing.Timer{
public SwingTimer(int delay, ActionListener listener) {
super(delay, listener);
}

private static final long serialVersionUID = -3852085911769548093L;

public static void main(String[] args) {
final int delay = 200;
final int[] count = new int[10];

SwingTimer st = new SwingTimer(100, null);
for(int i=0; i<10; i++){
final int ii = i;
st.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
count[ii]++;
System.out.println("--run "+ii+" "+Thread.currentThread());
try {
Thread.sleep(delay);
} catch (InterruptedException ee) {
ee.printStackTrace();
}
}
});
}
st.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}

// st.setDelay(1000);
try {
Thread.sleep(3010);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
st.stop();

}
}


util Timer
package timer;

import java.util.TimerTask;

/**
* UtilTimer一旦运行,不能调整delay,若想停止单个任务,调用该任务的cancle()<br>
* util timer 强调执行的频率,而不在乎谁先谁后
* timer.schedule(),根据前一次执行的实际执行时间来安排每次执行,执行的频率一般要稍慢于指定周期的倒数,
* 如果由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则后续执行也将被延迟<br>
* timer.scheduleAtFixedRate(),根据已安排的初始执行时间来安排每次执行,执行的频率将正好是指定周期的倒数,
* 如果由于任何原因(如垃圾回收或其他背景活动)而延迟了某次执行,则将快速连续地出现两次或更多的执行,
* 从而使后续执行能够“追赶上来”<br>
* @author Administrator
*
*/
public class UtilTimer extends java.util.Timer{

public static void main(String[] args) {
final int delay = 1;
final int[] count = new int[10];
UtilTimer ut = new UtilTimer();
for(int i=0; i<10; i++){
final int ii = i;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {

count[ii]++;
System.out.println("tt"+ii+" run "+Thread.currentThread());
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
};
ut.scheduleAtFixedRate(timerTask, 20, 100);//AtFixedRate
}

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ut.cancel();
for(int l : count){
System.out.print(l+" ");
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值