Java timer (Timer) and thread pool using timer instance code

  • 2020-05-26 08:33:44
  • OfStack

java Timer timer

Simple example code:


public class Test {


  public static void main(String[] args) {


    // Timer The timer 

    Timer mTimer = new Timer();
    MyTack myTack = new MyTack();
    mTimer.schedule(myTack, 2000, 3000);// The first 1 The parameters are the tasks that need to be performed   The first 2 The number of arguments is how long to delay the initial execution, the first 3 The parameters are how much time it takes to execute again 1 Individual periodic 
    Scanner mScanner = new Scanner(System.in);
    String exti = "";
    while(!exti.equals("1")){
      System.out.println("---->>");
      exti = mScanner.next();
    }
    System.out.println(" Shut down ");
    mTimer.cancel();// Turn off the timer 
    mScanner.close();
  }

  static class MyTack extends TimerTask{

    @Override
    public void run() {
      System.out.println(" Perform a task ");

    }

  }
}

The timer in the thread pool


public class Test {

  public static void main(String[] args) {

    //  The timer 
    ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
    service.scheduleWithFixedDelay(new MyRunnable(), 0, 10000,
        TimeUnit.MILLISECONDS);//1 All parameters are instantiated 1 a runnable The object of 2 The parameters are how long the delay is after execution, and the 3 Two parameters are execution 1 How long do you need to wait after the first execution 2 Time is 1 One periodic, one 4 The parameters are calculated by type ( Milliseconds, seconds, minutes. other 1 Some types of ).
  }

}

// Need to write 1 An implementation runnable The class of the interface 
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();
      }
    }

  }

}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: