简体   繁体   中英

Thread pool with wait for execution of task in java

I want to create a thread pool code in java where task will wait until the function called in task in completed. I have gone through many examples but cannot achieve my goal so far.

public class ThreadController {

    public static void main(String args[]) {
        ExecutorService service = Executors.newFixedThreadPool(5);

        List<String> list = new ArrayList<String>();
        list.add("john");
        list.add("reck");
        list.add("moni");
        list.add("sasha");
        list.add("pely");
        for (int p = 0; p < 100; p++) {
            for (int r = 0; r < 5; r++) {
                Task task = new Task(list.get(r));
                service.submit(task);
            }
        }
    }
}

final class Task implements Runnable {

    private String taskSimNo;

    public Task(String no) {
        this.taskSimNo = no;
    }

    public void run() {
        Initiate.startingInitiate(this.taskSimNo);
    }
}

The complete idea of this function is to call a function processing() which is a method of mainMethod class. So i want to run 10 threads in parallel but, 11th task should only start when any of the 10 tasks gets finish executing so I need to implement wait function to let the task complete. Any suggestions please.

Your synchronized block with task.wait() does nothing but blocking the loop since there is at no point a call to the notify method. So you first of all need to remove that.

Secondly, your processing method does not benefit from any multi-threading, because it is called within the constructor and object creation is done by the main thread. Solution is to move your processing method down inside the run method.

You correctly assigned a limit to the thread pool allowing 10 concurrent tasks to run.

Note: Order is not ensured! Task 11 might run before task 8 for example.

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