1

Hello I have this custom TimerTask :

public class TimerTaskPerso extends TimerTask {
private static boolean i =  false;
@Override
public void run() {
    System.out.println(i);
    if(i){
        System.out.println("m here");
        return;
    }
    i= true;
    System.out.println("ok");

    try {
        Thread.sleep(3000);
    } catch (InterruptedException ignored) {

    }
    System.out.println("bye");
    i= false;
}
}

And I am calling it like that :

new Timer().schedule(new TimerTaskPerso(), 1,500);

But the task keeps showing :

false
ok
bye
false
ok
false

I am supposed to see "m here" message, I tried this without creating Custom TimerTask and by using AtomicBoolean but same result.

Thanks in advance,

younes zeboudj
  • 856
  • 12
  • 22

2 Answers2

0

When the TimerTask's run method starts, i will be false. Then it is set to true. But after sleeping for 3 seconds, i is again set to false.

During the next run, i will start off as false. And this goes on..

You have to remove you last assignment to i to make it become true after the first run. With this, it will print m here on subsequent runs.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • But when sleeping for 3000 millis, there will be other tasks executed at a rate of 1 every 500 millis, based on this, some run() calls should occurs while i is true, check the timer schedule I've included in the question – younes zeboudj Dec 31 '19 at 04:32
0

Why you are thinking it will print "m here" as output. You are setting i=false again. So it will not print that message. In order to print that message you should comment this line i= false;. After commenting this line the output in my IDE is:

false
ok
bye
true
m here
true
m here

Please go through these for more information on static variables: static variables in multithreading and this also Are static variables shared between threads?

P3arl
  • 383
  • 3
  • 18