简体   繁体   English

Java执行程序:如何在执行程序中通知单个等待线程?

[英]Java executors: How to notify a single waiting thread within the executer?

So here is what I'm trying to accomplish: 因此,这就是我要完成的工作:

I have a FixedThreadPool with 5 Threads in it. 我有一个5个线程的FixedThreadPool。 Those threads just sit there and wait to be notified. 这些线程只是坐在那里,等待被通知。 When notified, the thread within the pool starts to do stuff. 收到通知后,池中的线程开始执行操作。

Now, whenever some triggering event occurs, one and only one waiting thread within the pool must be notified. 现在,无论何时发生某些触发事件,都必须通知池中只有一个等待线程。 Is it possible to accomplish this at all? 是否有可能完全做到这一点?

Here is what I tried, but i get an IllegalMonitorStateException: 这是我尝试过的,但是得到了IllegalMonitorStateException:

public class Server {
    private class WorkerThread implements Runnable{ 
        private Object lock = null;

        WorkerThread(Object lock){
            this.lock = lock;
        }

        public void run() {
            try{
                do{
                    synchronized(lock){
                        wait();
                    }
                    // doSomeThing
                }while(true);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    private ExecutorService executor = null;
    private Object lock = new Object();

    Server() {
        executor = Executors.newFixedThreadPool(5);
        for(int i=0; i<5; i++){
            executor.execute(new WorkerThread(lock));
        }
    }

    public void calledWhenTriggerEventOccurs(){
        synchronized(lock) {executor.notify();}
    }
}

Object.notifyAll notifies all threads waiting on this Object's monitor. Object.notifyAll通知所有在此对象的监视器上等待的线程。 Object.notify notifies one (random) thread waiting on the monitor. Object.notify通知一个(随机)线程在监视器上等待。 Is this what you were looking for? 这是您要找的东西吗?

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

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