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();
}
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!