Reputation: 315
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?
Upvotes: 0
Views: 1523
Reputation: 3519
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 an anonymous class implementing Runnable. You are not starting the thread yourself and the code works as expected.
Upvotes: 1
Reputation: 3289
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");
}
}
Upvotes: 1