繁体   English   中英

如何在线程中使用wait()和notify()进行命令处理

[英]How to use wait() and notify() for command processing in thread

我有Java线程类,目的是在命令到达时对其进行处理。 我当前的实现使用Thread.sleep(50)来检查新命令,但是我想使用wait / notify使它更加优雅。 如何在不引入错误的情况下做到这一点? 这是我的代码:

protected BlockingQueue<Command> currentCmds = new LinkedBlockingDeque<Command>();

@Override
public void run() { 
    while (!dead) {
        Thread.sleep(50);
        if (!currentCmds.isEmpty()) {           
            Command cmd = currentCmds.remove();
            processCmd(cmd);
        }
    }
}

public void sendCommand(Command command) {
    currentCmds.add(command);
}

我怀疑当许多客户端连接时,这种方法会使我的服务器速度变慢。

我有Java线程类,目的是在命令到达时对其进行处理。

基本上,您需要一个ExecutorService,它是一个线程池和一个队列。

private final ExecutorService es = Executors.newSingleThreadExecutor();

public void sendRunnable(Runnable run) {
    es.submit(run);
}

public void sendCommand(Command command) {
    es.submit(new Runnable() {
       public void run() {
           try {
               command.call();
           } catch (Throwable t) {
               t.printStackTrace();
           }
       }
   });
}

甚至更简单的解决方案是只提交Runnable或Callable而不使用Command。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM