Здравствуйте, уважаемые.
Возникла потребность обработать N задач M потоками. Я слышал о готовом решении ThreadPoolExecutor, который почти подходит. Есть только проблема: необходимо чтоб на время выполнения этой массовой задачи, текущий поток остановился и по выполнении определенного числа задач возобновил работу.
Моё решение на скорую руку:
Код | class AmountExecutor extends ThreadPoolExecutor {
private int tasksAmount;
private AmountExecutor(int simulteniousJobs, int tasksAmount) { super(simulteniousJobs, simulteniousJobs, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(tasksAmount)); this.tasksAmount = tasksAmount; }
protected synchronized void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); tasksAmount--; if (tasksAmount == 0) { notifyAll(); } } }
|
Код запуска:
Код | ThreadPoolExecutor threadPool = new AmountExecutor(simulteniousJobs, tasks.size()); for (Runnable r : tasks) threadPool.execute(r); try { synchronized (threadPool) { threadPool.wait(); } threadPool.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); }
|
В целом, и такое устроит. Но, как недавно вычитал, "наличие опыта не говорит о его ценности". Главное - знание. так вот хочется знать лучшее решение. |