首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >避免线程中出现忙碌等待警告

避免线程中出现忙碌等待警告
EN

Stack Overflow用户
提问于 2021-11-15 13:02:17
回答 2查看 168关注 0票数 1

我有一段代码:

代码语言:javascript
运行
复制
public void foo(AtomicBoolean close){

    new Thread(() -> {

        try{

            System.out.println("foo started");

            while(!close.get()){

                System.out.print("working");
                //peace of code for execution.

                //wait 1 second before re-execute the same thing.
                //warning: Call to 'Thread.sleep()' in a loop, probably busy-waiting
                try{ Thread.sleep(1_000); /*1sec*/ }catch(Exception ignored){}

            }

        }catch(Exception e){
            e.printStackTrace();
        }

        System.out.println("foo stopped");
        

    }, "fooThread").start();

}

代码可以工作,但我想摆脱那个警告,并且我不知道如何重写这段代码。

close只是为了知道线程什么时候应该停止。

EN

Stack Overflow用户

回答已采纳

发布于 2021-11-15 16:22:39

我就是这么写的。您不一定需要这个类,它只是很好地封装了执行器和任务。

除了scheduleWithFixedDelay之外,还有scheduleAtFixedRate。不同之处在于explained here。我选择了最接近您的代码的代码。

代码语言:javascript
运行
复制
class FooService
{ 
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    private volatile ScheduledFuture<?> task;
    
    public void start() {
        if (task != null) {
            throw new RuntimeException("Already started");
        }

        task = executor.scheduleWithFixedDelay(() -> {
            System.out.println("working");
            // piece of code for execution.
        }, 0, 1, TimeUnit.SECONDS);
    }
    
    public void stop() {
        task.cancel(true);
        executor.shutdown();
    }
}
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69974804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档