Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Runnable objects

Is there any way that I can run a fixed maximum amount of threads in parallel and REUSE the Runnable object as soon as one of the threads finishes? So, given N sets of running parameters for Runnable obj and only M Runnable objects (M < N) is there a way to make sure that as soon as one of the threads using a Runnable object finishes, I start a new thread using the same Runnable obj (thus a maximum of M threads running at one time) ?

like image 444
Mahu Avatar asked Sep 14 '26 12:09

Mahu


1 Answers

You can implement Producer-Consumer pattern like:

    int n = 10;
    Executor executor = Executors.newFixedThreadPool(n);
    final BlockingQueue<Object> tasks = new ArrayBlockingQueue(1024);
    for (int i = 0; i < n; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Object task = tasks.take();
                        // process task
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }
    tasks.put(new Object());
like image 186
Denis Borovikov Avatar answered Sep 16 '26 02:09

Denis Borovikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!