Timer定时器
public class Test {
public static void main(String[] args) {
Timer mTimer = new Timer();
MyTack myTack = new MyTack();
mTimer.schedule(myTack, 2000, 3000);
Scanner mScanner = new Scanner(System.in);
String exti = "";
while(!exti.equals("1")){
System.out.println("---->>");
exti = mScanner.next();
}
System.out.println("关闭");
mTimer.cancel();
mScanner.close();
}
static class MyTack extends TimerTask{
@Override
public void run() {
System.out.println("执行任务");
}
}
}
线程池里的定时器
public class Test {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.scheduleWithFixedDelay(new MyRunnable(), 0, 10000,
TimeUnit.MILLISECONDS);
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
int index = 0;
while (index++ < 100) {
System.out.println(Thread.currentThread().getName()+" "+index);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}