Pass parameters to Timer Task (Java)

2019-04-06 11:32发布

I have a timer task in a loop;

I want to pass into the time task which number it is in a loop...

Is that possible?

My code:

...
int i = 0;
while (i < array.size){
    Timer timer = new Timer();
    timer.schedule(new RegrowCornAnimate(), 0, 1000);
i++
}
...

class RegrowCornAnimate extends TimerTask {
     public void run() {
//Do stuff
   }
}

How can I change it so I can use i in the TimerTask class? -as in each TimerTask will know which i it was created under/in/from.

Thanks,

标签: java timer
4条回答
爷、活的狠高调
2楼-- · 2019-04-06 11:40

Create a constructor in RegrowCornAnimate taking the parameters you'd like to use, then store them as members inside your class.

When RegrowCornAnimate.run is called read the values.

查看更多
等我变得足够好
3楼-- · 2019-04-06 11:48

Please see an example at http://www.roseindia.net/java/task-scheduling.shtml. This example prints a number with each run.

查看更多
叛逆
4楼-- · 2019-04-06 11:51

Give the RegrowCornAnimate class a constructor that takes an int and store that in a field. Pass i to the constructor when you create it.

查看更多
Explosion°爆炸
5楼-- · 2019-04-06 12:01
class RegrowCornAnimate extends TimerTask {

    private final int serial;


    RegrowCornAnimate ( int serial )
    {
      this.serial = serial;
    }

    public void run() {
      //Do stuff
    }
}

...
int i = 0;
while (i < array.size){
    Timer timer = new Timer();
    timer.schedule(new RegrowCornAnimate( i ), 0, 1000);
    i++;
}
...
查看更多
登录 后发表回答