【问题标题】:calling particluar function after delay in java [closed]在java中延迟后调用特定函数[关闭]
【发布时间】:2020-02-11 18:35:24
【问题描述】:

java中延迟后如何调用特定函数?

{

// Do something 

   callmeafterevery10sec () // call this function in every 10 sec while continue the whole thing 

 // Do something

}

【问题讨论】:

  • 听起来像是 ScheduledExecutorService 的作业。您应该查看此类的 JavaDoc。有很好的例子。

标签: java multithreading timer


【解决方案1】:

选项 1:

Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 10000);

这将每 10 秒打印一次Hello World。您可以在方法中使用 this,也可以使用 this 调用另一个方法。

选项 2:

来自 Brian Goetz 等人的 Java 并发实践ScheduledExecutorService 更好:

Runnable helloRunnable = new Runnable() {
    public void run() {
        System.out.println("Hello world");
    }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);

更多关于 ScheduledExecutorService.scheduleAtFixedRate here.

【讨论】:

  • @parikshitparmar,如果它解决了您的问题,请不要忘记接受答案。
  • 第一个解决方案不起作用,它卡在了 run 方法中。不能同时执行其他方法。
  • 您可以编辑并提出您刚刚尝试过的问题吗?我会试着看看它。因为它对我有用。
  • 导入 java.util.Timer;导入 java.util.TimerTask;类 TestThread { public static void main(final String[] arguments) throws InterruptedException { Timer t = new Timer(); System.out.println("第一次打印"); t.schedule(new TimerTask() { @Override public void run() { printSomething(); } }, 0, 100); System.out.print("最后一次打印"); } public static void printSomething(){ System.out.print("Inside It"); } }
  • 我试图编辑我的帖子,但此时我似乎不可能添加代码,它显示按 ctrl +k 和 4 个空格缩进
【解决方案2】:

只需调用 Thread.sleep() 即可:

public class Test {
    public static void main(String args[]) throws InterruptedException {    
        useTimer();
    }

    private static void useTimer() throws InterruptedException {
        System.out.println("**********");
        Thread.sleep(10000);
        System.out.println("----------");

    }
}

【讨论】:

  • @parikshitparmar 如果可行,请接受答案,否则请告诉我是否仍然面临问题
  • OP 示例中的一条评论说:“每 10 秒调用一次此函数,同时继续整个过程。”这听起来很像是他们想在后台线程中执行周期性任务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 2016-03-22
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多