有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java编写刷新线程的最佳方法

您好,我有一些配置,这些配置将在可配置的时间跨度后刷新。做这件事的最好方法是什么,或者遵循什么就足够了

@Override
    public void run()
    {
        try
        {
            while(true){
                if (isRefreshNeeded) {
                    refresh()
                }
            }
        }
        catch( Exception excep )
        {
            // Log and report exception 
        }
    }

共 (5) 个答案

  1. # 2 楼答案

    java中有一个最干净的选项。utl。并发的ScheduledExecutorService#scheduleAtFixedRate

    Here是API文档

  2. # 3 楼答案

    除了在一段时间后使用Timer/TimerTask或更现代的ScheduledExecutorService/Runnable方法进行刷新之外,您或许应该使用侦听器(又称观察者)模式在更改和刷新之间建立因果关系。 如果您对所发布的代码更熟悉,那么至少应该在while循环的末尾使用Thread.sleep()

  3. # 4 楼答案

    我建议使用Timer类,这就是它的用途

    使用代码不是一个好主意,因为它会一直重复,从而消耗CPU周期

  4. # 5 楼答案

    使用Timer类尝试以下操作:

    long initialDelay = 100; // In millis
        long delay  = 1000; // In millis
    
        Timer timer = new Timer("Refresher thread");
        timer.schedule(new TimerTask() {
    
            @Override
            public void run() {
                // code to refresh the configurations
    
            }
        }, initialDelay, delay);