尽管所有 Timer 都使用一个共享线程(由第一个执行操作的 Timer 对象创建)执行等待,但是 Timer 的动作事件处理程序还会在其他线程(事件指派线程上)执行。这意味着 Timer 的操作处理程序可以安全地在 Swing 组件上执行操作。但是,它也意味着处理程序必须快速执行以保证 GUI 作出响应。
java.util.Timer
一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。
简单理解,javax.swing.Timer没有增加线程,利用事件线程的间隙运行,java.util.Timer增加线程了。
public class Test {Thread th1 = new Thread(new Th1())//定义线程1
Thread th2 = new Thread(new Th2())//定义线程2
public Test() {
this.th1.start()
this.th2.start()
}
public static void main(String[] args) {
new Test()
}
// 线程1
class Th1 implements Runnable {
public void run(){
while(true){
System.out.println("我是线程1")
try {
th1.sleep(1000)//一秒后再此运行
} catch (Exception ex) {
ex.printStackTrace()
}
}
}
}
// 线程2
class Th2 implements Runnable {
public void run(){
while(true){
System.out.println("我是线程2")
try {
th2.sleep(3000)//3秒后再此运行
} catch (Exception ex) {
ex.printStackTrace()
}
}
}
}
}
定时器不会提前执行。基础知识java.util.Timer一种线程设施,用于安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。此类是线程安全的:多个线程可以共享单个Timer对象而无需进行外部同步。java.util.TimerTask由Timer安排为一次执行或重复执行的任务。