Java 定时器(Timer)及线程池里使用定时器实例代码
javaTimer定时器
简单实例代码:
publicclassTest{
publicstaticvoidmain(String[]args){
//Timer定时器
TimermTimer=newTimer();
MyTackmyTack=newMyTack();
mTimer.schedule(myTack,2000,3000);//第一个参数是需要执行的任务第二个参数是延迟多少时间最开始执行,第三个参数是执行完后多少时间后进行再次执行是一个周期性的
ScannermScanner=newScanner(System.in);
Stringexti="";
while(!exti.equals("1")){
System.out.println("---->>");
exti=mScanner.next();
}
System.out.println("关闭");
mTimer.cancel();//关闭这个定时器
mScanner.close();
}
staticclassMyTackextendsTimerTask{
@Override
publicvoidrun(){
System.out.println("执行任务");
}
}
}
线程池里的定时器
publicclassTest{
publicstaticvoidmain(String[]args){
//定时器
ScheduledExecutorServiceservice=Executors.newScheduledThreadPool(3);
service.scheduleWithFixedDelay(newMyRunnable(),0,10000,
TimeUnit.MILLISECONDS);//一个参数是实例化一个runnable的对象,第二个参数是延迟多长时间后执行,第三个参数是执行一次后需要等待多长时间后执行第二次是一个周期性的,第四个参数是按类型算(毫秒,秒,分。。等其他的一些类型).
}
}
//需要写一个实现runnable接口的类
publicclassMyRunnableimplementsRunnable{
@Override
publicvoidrun(){
intindex=0;
while(index++<100){
System.out.println(Thread.currentThread().getName()+""+index);
try{
Thread.sleep(50);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下