Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a simple queue with Java threads

I'm trying to create a simple queue with Java Thread that would allow a loop, say a for loop with 10 iterations, to iterate n (< 10) threads at a time and wait until those threads are finished before continuing to iterate.

Here's a better way to illustrate my problem:

for (int i = 1; i <= 10; i++) {
    new Thread ( do_some_work() );

    if ( no_available_threads ) {
        wait_until_available_threads();
    }
}

do_some_work() {
    // do something that takes a long time
}

Basically what I want to do is a copy of this: Thread and Queue

How can I achieve this the most painless way?

like image 980
ioni Avatar asked Mar 28 '12 21:03

ioni


People also ask

Is queue in Java thread-safe?

Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control. Java BlockingQueue interface is part of java collections framework and it's primarily used for implementing producer consumer problem.

How do you create a thread in Java?

You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a thread object and call the start() method. Thread Class: The Thread class provides constructors and methods for creating and operating on threads.

How do you create a queue in FIFO in Java?

For ArrayDeque to function as a queue (FIFO) rather than a stack (LIFO), you should use add and remove . If you use push and pop , it behaves as a stack. (Strictly speaking, remove and pop are the same, but since add/pop or push/remove don't sound good as pairs, we go with add/remove and push/pop .)


1 Answers

I would use the Java 5 Executors instead of rolling your own. Something like the following:

ExecutorService service = Executors.newFixedThreadPool(10);
// now submit our jobs
service.submit(new Runnable() {
    public void run() {
        do_some_work();
    }
});
// you can submit any number of jobs and the 10 threads will work on them
// in order
...
// when no more to submit, call shutdown, submitted jobs will continue to run
service.shutdown();
// now wait for the jobs to finish
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
like image 154
Gray Avatar answered Oct 01 '22 00:10

Gray