简体   繁体   中英

Max. created Threads with Threadpool Java

I have to write a code for concurrent Mergesort and my problem is, if the merge sort implementation wants to create a new thread, it has to check if there is a thread slot available or not ( so i created a Threapool(max 5 Threads).It is also working, but my problem is that i should only use 5 threads without reusing them.

That means if there are no more thread slots available the thread just performs for its array part the traditional recursive merge sort algorithm.

    int nThreads = 5;
    ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    for (int i = 1; i < 10; i++){
        Runnable worker = new Mergesort(array);
        executor.execute(worker);           
    }
    executor.shutdown();

    while(!executor.isTerminated()) {

    }   

There are some ways to do that as mentioned in this SO answer . Especially refer to the answer by user danben .

However, you need to make sure to yourself that the count of 5 which you state includes the main thread also or not - that is does the count of 5 mean mainthread + 4 threads or 5 worker threads.

Hope this points you in a direction to solve your problem.

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