简体   繁体   中英

scheduleAtFixedRate executes task immediately, should run after defined delay.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class MyTask1 implements Runnable{
MyTask1(){
    new Thread(this).start();
}
public void run(){
    System.out.println("Running");
}
}
public class Schedular_1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
    ex.scheduleAtFixedRate(new MyTask1(), 3, 10, TimeUnit.SECONDS); 
  }

 }

scheduleAtFixedRate 's first run is expected after delay we defined in 2nd parameter. And subsequent execution has to be defined by 3rd parameter ie every 10 seconds. But actually it(MyTask1) is running immediately as soon as I invoke main method. after 3 seconds it executes for 2nd time and after every 10 seconds it runs periodically.

I got another version of this that works fine available here ( link ).

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class MyTask1 implements Runnable{
MyTask1(){
    new Thread(this).start();
}
public void run(){
    System.out.println("Running");
}
}
public class Schedular_1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
    ex.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println("Testing...");
        }
    }, 3, 10, TimeUnit.SECONDS);
}

}

What is the difference between these 2 veriations. Why it behaves abnormally?

The problem in your code is that you are starting a Thread in the constructor:

MyTask1(){
    new Thread(this).start();
}

When you execute scheduleAtFixedRate , you are creating a new instance and starting a new thread. Then the ExecutorService run the task as expected.

In your second version, you defined a anonymous class implementing Runnable. You are not starting the thread yourself and the code works as expected.

You don't need start Thread in your MyTask1 . The correct version of MyTask1 is going to be:

class MyTask1 implements Runnable{
    MyTask1(){
    }
    public void run(){
        System.out.println("Running");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM