How to override the shutterService method

I create my own thread pool and a future object that can execute the called interface in parallel. Executor provides a stop method to stop all worker threads. If I create a thread pool as shown below, how should I implement the shutdown method to stop after all threads have completed?

My custom thread pool looks like this

class MyThreadPool implements java.util.concurrent.Executor 
{
    private final java.util.concurrent.BlockingQueue<Callable> queue;

    public MyThreadPool(int numThreads) {
        queue = new java.util.concurrent.LinkedBlockingQueue<>();
        for (int i=0 ; i<numThreads ; i++) {
            new Thread(new Runnable(){
                @Override
                public void run() {
                    while(true) {
                        queue.take().call();
                    }
                }
            }).start();
        }
    }

  @Override
  public <T> Future<T> submit(Callable<T> callable) {
    FutureTask<T> future = new FutureTask(callable);
    queue.put(future);
    return future;
  }

  public void shutdown(){ }
}

I could not think of a way to save the list of threads and then check if they are idle or not?

+4
source share
1 answer

. , threads List<Thread> .

shutdown() Thread#join():

public void shutdown() {
    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException e) { /* NOP */ }
    }
}

while (true) ( shutdown()) BlockingQueue#poll(long, TimeUnit) take().

EDIT: - :

public class MyThreadPool implements Executor {

    private List<Thread> threads = new ArrayList<>();
    private BlockingDeque<Callable> tasks = new LinkedBlockingDeque<>();
    private volatile boolean running = true;

    public MyThreadPool(int numberOfThreads) {
        for (int i = 0; i < numberOfThreads; i++) {
            Thread t = new Thread(() -> {
                while (running) {
                    try {
                        Callable c = tasks.poll(5L, TimeUnit.SECONDS);
                        if (c != null) {
                            c.call();
                        }
                    } catch (Exception e) { /* NOP */ }
                }
            });
            t.start();
            threads.add(t);
        }
    }

    public void shutdown() {
        running = false;
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) { /* NOP */ }
        }
    }

    // ...

}
+1

Source: https://habr.com/ru/post/1657882/


All Articles