欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 定时器(Timer)及线程池里使用定时器实例代码

程序员文章站 2024-03-08 21:32:34
java timer定时器 简单实例代码: public class test { public static void main(string[...

java timer定时器

简单实例代码:

public class test {


  public static void main(string[] args) {


    // timer定时器

    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);//一个参数是实例化一个runnable的对象,第二个参数是延迟多长时间后执行,第三个参数是执行一次后需要等待多长时间后执行第二次是一个周期性的,第四个参数是按类型算(毫秒,秒,分。。等其他的一些类型).
  }

}

//需要写一个实现runnable接口的类
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) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
    }

  }

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!