swing Timer
util 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+" ");
}
}
}