使用while(true) Thread.sleep()可控性很低的改进

做各种SERVICE的时候,常常会需要一个程序重复定时地执行,基本上常见的写法都是如下所示:

public void run(){
  while(true){
   try {

        System.out.println("yours code");

       } catch (Exception e) {
    e.printStackTrace();
   }
   try {
    this.sleep(2000L);           

   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 public static void main(String[] args){
  new TestThread().start();
 }

但实际这样的写法可控性很低,JDK的java.util.concurrent中提供了大量的方法去控制一段代码定时执行,标准的改写上面的代码如下:

public void run() {
  System.out.println("yours code");
   }
 
 public static void main(String[] args){
  ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  scheduler.scheduleWithFixedDelay(new TestThread(), 0, 3, TimeUnit.SECONDS);
 }

你可能感兴趣的:(java,thread)