您的位置:首页 > 职场人生

黑马程序员——Java基础---线程的另一个总结(2)--定时器

2015-07-01 21:39 716 查看
定时器:

定时一次任务
public class TraditionalTimerTest {
public static void main(String[] args) throws InterruptedException {
new Timer().schedule(new TimerTask() {

@Override
public void run() {
System.out.println("定时5秒");

}
}, 5000);
while(true){
System.out.println(new Date().getSeconds());
Thread.sleep(1000);
//			System.out.println(System.currentTimeMillis());

}
}

}


定时间隔一定时间执行一次

public class TraditionalTimerTest {
public static void main(String[] args) throws InterruptedException {
new Timer().schedule(new TimerTask() {

@Override
public void run() {
System.out.println("3秒执行一次");

}
}, 5000,3000);

}

}
方法中调用方法,使用死循环实现定时任务

public class TraditionalTimerTest {
public static void main(String[] args) {

class MyTimerTask extends TimerTask{

@Override
public void run() {

System.out.println("bombing!");
new Timer().schedule(new MyTimerTask(),2000);
}
}

new Timer().schedule(new MyTimerTask(), 4000);

while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: