java - 调用FutureTask的run方法时如何消除sonar qube问题?

标签 java multithreading sonarqube futuretask

我有以下代码,Sonar Qube 引发了严重错误。

public void onMessageReceived(Message message) {

    if((message.getTargetInstanceId() != Message.ANY_TARGET) && (message.getTargetInstanceId() != this.instanceId)) {
        //Invalid message ignore
        return;
    } else {
        int randTime = ran.nextInt(2000);
        FutureTask<Message> workerTask = new FutureTask<>(new DummyCommandHandler(randTime, message,messageBus,instanceId)); 
        workerTask.run();
    }


}

以下是我遇到的问题。

Description Assignee    Resource    New issue
Thread.run() and Runnable.run() should not be called directly : Call the method Thread.start() to execute the content of the run() method in a dedicated thread.        

要在FutureTask中调用start方法,它本来就没有start方法。它只有一个 run 方法。我怎样才能克服这个问题?有Java解决方案或Sonarqube解决方案吗?请指教。

最佳答案

SonarQube 是对的,您不应该直接调用 futureTask.run()。使用 ExecutorService 代替:

ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(futureTask1);

This是关于该主题的简短而良好的教程。

关于java - 调用FutureTask的run方法时如何消除sonar qube问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952500/

相关文章:

java - 如何转换 ByteArrayOutputStream 以便使用 readline 循环

java - double 和 Double 比较的区别

ios - 发送 NSNotification 时,CustomCell 中的 UIProgressView 从不显示

python - sklearn 管道的并行化

sonarqube - 如何在 Eclipse 中启用/禁用来自 SonarLint 的任何规则

gradle - Gradle Powermock代码覆盖丢失

hudson - 为什么 jenkins 中的 Sonar 插件会重新构建所有内容?

java - Tomcat 8 文件下载速度问题

c# - 协助 UI Dispatcher 处理大量的方法调用

java - 在 Android 应用程序中读取文件需要太多时间