Create a simple queue with Java threads

前端 未结 4 669
终归单人心
终归单人心 2020-12-17 02:37

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 tho

4条回答
  •  感动是毒
    2020-12-17 03:35

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

提交回复
热议问题