简体   繁体   中英

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

I have Java thread class which purpose is to process commands when they arrive. My current implementation uses Thread.sleep(50) for checking for new commands, but I want to make it more elegant using wait/notify. How to do that without introducing bugs ? Here is my code:

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);
}

I suspect this approach is slowing down my server when many clients are connected.

I have Java thread class which purpose is to process commands when they arrive.

Basically you want an ExecutorService which is a thread pool and a queue in one.

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();
           }
       }
   });
}

An even simpler solution is to just submit Runnable or Callable and not use Command at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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