请问这是怎么安排的Java方法以后运行1秒?这是、方法、Java

2023-09-05 06:30:13 作者:我心切望

在我的方法,我要打电话,这将在以后运行1秒另一种方法。这就是我。

In my method, I want to call another method that will run 1 second later. This is what I have.

final Timer timer = new Timer();

timer.schedule(new TimerTask() {
    public void run() {
          MyMethod();
          Log.w("General", "This has been called one second later");
        timer.cancel();
    }
}, 1000);

请问这是怎么它应该做些什么呢? 还有没有其他的方法可以做到这一点,因为我在Android? 它可以被重复没有任何问题?

Is this how it's supposed to be done? Are there other ways to do it since I'm on Android? Can it be repeated without any problems?

推荐答案

而不是一个定时器,我会建议使用ScheduledExecutorService

Instead of a Timer, I'd recommend using a ScheduledExecutorService

final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);

exec.schedule(new Runnable(){
    @Override
    public void run(){
        MyMethod();
    }
}, 1, TimeUnit.SECONDS);