user1875195
user1875195

Reputation: 988

Java concurrency with queues

What I am trying to do is basically kick off new threads, add them to a queue, and than execute the rest of the code when they are dequeued. I'm not sure what the best way to add them to a queue, and how I can pause a thread at a point and notify them when they are dequeued. I haven't really done too much concurrent programming in Java before. Any help or suggestions would be greatly appreciated! Thanks

Upvotes: 2

Views: 204

Answers (2)

ddmps
ddmps

Reputation: 4380

wait() and notify() can be used for this, as such:

class QueuedThread extends Thread {
    private volatile boolean wait = true; //volatile because otherwise the thread running run() might cache this value and run into an endless loop.

    public void deQueue() {
        synchronized(this) {
            wait = false;
            this.notify();
        }
    }

    public void run() {
        synchronized(this) {
            while (wait) { //You need this extra mechanism because wait() can come out randomly, so it's a safe-guard against that (so you NEED to have called deQueue() to continue executing).
                this.wait();
            }
        }
    //REST OF RUN METHOD HERE
    }
}

Just call queuedThread.deQueue() when it should be de-queued.

Upvotes: 1

Mik378
Mik378

Reputation: 22171

You could use a ThreadPoolExecutor, basically creating a pool of threads according to multiple customizable rules.

And to be sure that all threads have done their respective job before your process goes on the remaining code, you just have to call ThreadPoolExecutor's awaitTermination method preceded by an eventual ThreadPoolExecutor's shutdown method.

You could also send a notify/notifyAll after the call to awaitTermination in order to wake up some other result-dependent threads.

A sample is written in the ExecutorService documentation (implemented by ThreadPoolExecutor).

Upvotes: 4

Related Questions