Executes the tasks using a thread pool and returns once all tasks have
finished.

@throws IllegalStateException if interrupted while waiting for the tasks
to finish
327800
public void run(Collection<Runnable> tasks) {
        // Create a semphore that the wrapped runnables will execute
        int numTasks = tasks.size();
        CountDownLatch latch = new CountDownLatch(numTasks);
        for (Runnable r : tasks) {
            if (r == null)
                throw new NullPointerException("Cannot run null tasks");
            workQueue.offer(new CountingRunnable(r, latch));
        }
        try {
            // Wait until all the tasks have finished
            latch.await();
        }
        catch (InterruptedException ie) {
            throw new IllegalStateException("Not all tasks finished", ie);
        }
    }
74089
@Override
    public void run() {

        boolean runOnce = (m_runnable != null);

        while (m_run) {
            setPriority(m_pool.getThreadPriority());
            try {
                if (m_runnable == null) {
                    m_runnable = m_pool.getNextRunnable();
                }

                if (m_runnable != null) {
                    m_runnable.run();
                }
            } catch (InterruptedException e) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_THREAD_INTERRUPTED_1, getName()), e);
            } catch (Throwable t) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_THREAD_ERROR_1, getName()), t);
            } finally {
                if (runOnce) {
                    m_run = false;
                }
                m_runnable = null;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_THREAD_SHUTDOWN_1, getName()));
        }
    }
371779
private void runTasks() {
        //don't run anything in the IO thread till the tasks are done
        delegate.getSinkChannel().suspendWrites();
        delegate.getSourceChannel().suspendReads();
        List<Runnable> tasks = new ArrayList<>();
        Runnable t = engine.getDelegatedTask();
        while (t != null) {
            tasks.add(t);
            t = engine.getDelegatedTask();
        }

        synchronized (this) {
            outstandingTasks += tasks.size();
            for (final Runnable task : tasks) {
                getWorker().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            task.run();
                        } finally {
                            synchronized (SslConduit.this) {
                                if (outstandingTasks == 1) {
                                    getWriteThread().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            synchronized (SslConduit.this) {
                                                SslConduit.this.notifyAll();

                                                --outstandingTasks;
                                                try {
                                                    doHandshake();
                                                } catch (IOException | RuntimeException | Error e) {
                                                    IoUtils.safeClose(connection);
                                                }
                                                if (anyAreSet(state, FLAG_READS_RESUMED)) {
                                                    wakeupReads(); //wakeup, because we need to run an unwrap even if there is no data to be read
                                                }
                                                if (anyAreSet(state, FLAG_WRITES_RESUMED)) {
                                                    resumeWrites(); //we don't need to wakeup, as the channel should be writable
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    outstandingTasks--;
                                }
                            }
                        }

                    }
                });
            }
        }
    }
634305
public void execute()
    {
        Runnable task = new Runnable()
        {
            public void run()
            {
                final V result = performTask();
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        postProcessing(result);
                        latch.countDown();
                    }
                });
            }
        };
        new Thread(task, "SwingBackgroundTask-" + id).start();
    }
760434
private synchronized void mainLoop() {
        for (Task task: taskDao.listTasks()) {
            if (task.getState().equals(Task.STARTING)) {
                startTask(task);
            } else if (task.getState().equals(Task.PAUSING)) {
                pauseTask(task);
            } else if (task.getState().equals(Task.RESUMING)) {
                resumeTask(task);
            } else if (task.getState().equals(Task.CANCELING)) {
                cancelTask(task);
            }
        }
        try {
            wait(POLL_SECONDS * 1000);
        } catch (InterruptedException e) {
        }
    }
412549
private Set<Location> waitForTasksCompleted() {
        try {
            Set<Location> targets = new HashSet<>();
            FutureTask<Set<Location>> task;
            while ((task = tasks.poll()) != null) {
                // wait for completion
                if (!task.isDone())
                    targets.addAll(task.get());
            }
            return targets;
        } catch (InterruptedException|ExecutionException e) {
            throw new Error(e);
        }
    }
1086893
public void waitUntilFinished()
    {
        flushTermination();
        flushUpdate();
        flushInsert();
        shutdown();
        for (int i = 0; i < numberOfUpdateThreads; i++)
        {
            while(!executor[i].isTerminated())
            {
                try
                {
                    executor[i].awaitTermination(10000000, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    // ignore
                }
            }
        }
        flushInsert();
        insertExecutor.shutdown();
        while(!insertExecutor.isTerminated())
        {
            try
            {
                insertExecutor.awaitTermination(10000000, TimeUnit.SECONDS);
            }
            catch (InterruptedException e)
            {
                // ignore
            }
        }
        logFinalResults();
        if (this.error != null)
        {
            if (error instanceof RuntimeException)
            {
                throw (RuntimeException) error;
            }
            else
            {
                throw new RuntimeException("One or more parallel tasks failed", this.error);
            }
        }
    }
658624
def perform
      unless @threads.any? { |t| t.alive? }
        @values.start!
        @size.times do
          @threads << Thread.new do
            while job = @queue.pop
              if job == :END_OF_WORK
                break
              else
                @values.push *job[1], &job[0]
              end
            end
          end
        end
      end
    end
1240223
public void waitUntilWorkDone(){
		while(objectListSize()>0 || getRunningThreadNumber()>0){
			if (stopped){
				log.fatal("El pool se ha parado de forma anormal. List Size:"+objectListSize()+" running threads:"+getRunningThreadNumber()+"/"+getThreadPoolSize());
				return ;
			}
			if (log.isDebugEnabled()){
				log.debug("List Size:"+objectListSize()+" running threads:"+getRunningThreadNumber()+"/"+getThreadPoolSize());
			}
			try {
				log.info("STILL WAITING List Size:"+objectListSize()+" running threads:"+getRunningThreadNumber()+"/"+getThreadPoolSize());

				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}

		log.info(" Calling threadWorkDone.");

		for (InnerConsumerThread thread:threadList) {
			try {
				// update the work done flag and notify thre thread
				thread.threadWorkDone();
				synchronized (thread) {
					thread.notify();
				}
			}catch(Throwable e){
				log.error("Error in threadWorkDone for thread:"+thread.getName(),e);
			}
		}
		
		synchronized (objectList) {
			objectList.notifyAll();		
		}

		if (log.isInfoEnabled()){
			log.info("Work, done. List Size:"+objectListSize()+" running threads:"+getRunningThreadNumber()+"/"+getThreadPoolSize());
		}
		
		log.info("FINISH: Work, done. List Size:"+objectListSize()+" running threads:"+getRunningThreadNumber()+"/"+getThreadPoolSize());

	}
227893
private void runTasks()
  {
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
    
    ThreadPoolBase pool = _pool;
    Thread thread = this;
    Outbox outbox = outbox();
    boolean isWake = false;

    setName(_name);
    
    while (! _isClose) {
      RunnableItem taskItem = pool.poll(isWake);
      isWake = false;
      
      if (taskItem != null) {
        try {
          _launcher.onChildIdleEnd();
          
          outbox.open();

          do {
            // if the task is available, run it in the proper context
            thread.setContextClassLoader(taskItem.getClassLoader());

            taskItem.getTask().run();
            
            outbox.flushAndExecuteAll();
          } while ((taskItem = pool.poll(false)) != null);
        } catch (Throwable e) {
          log.log(Level.WARNING, e.toString(), e);
        } finally {
          try {
            outbox.close();
          } catch (Throwable e) {
            e.printStackTrace();
          }
          
          _launcher.onChildIdleBegin();
          thread.setContextClassLoader(systemClassLoader);
          if (! thread.getName().equals(_name)) {
            setName(_name);
          }
        }
      }
      else if (_launcher.isIdleExpire()) {
        return;
      }
      else if (park()) {
        //thread.onWakeThread();
        isWake = true;
      }
      else {
        return;
      }
    }
  }
1173230
@Override
  public void run() {
    synchronized (lock) {
      if (!callables.hasNext()) {
        checkEnd();
        return;
      }

      for (int i = 0; i < parallelism && callables.hasNext(); i++) {
        setupNext(callables.next());
      }
    }

    future.whenCancelled(() -> {
      cancel = true;
      checkNext();
    });
  }
1143966
public void run()
   {
      this.currentThread = Thread.currentThread();
      this.running.set(true);

      while (this.running.get())
      {
         Task nextTask = null;
         try
         {
            if (_logger.isDebugEnabled())
               _logger.debug("Waiting for next task...");
            nextTask = this.taskSet.take();
            if (_logger.isDebugEnabled())
               _logger.debug("next from taskset is task: " + nextTask.getCommand());
            this.executor.submit(nextTask);
            if (_logger.isDebugEnabled())
               _logger.debug("submitted for execution command: " + nextTask.getCommand());
         }
         catch (InterruptedException e)
         {
            _logger.debug("Task manager thread interrupted.");
            this.running.set(false);
         }
         catch (Exception e)
         {
            _logger.debug("Task manager experienced an unhandled exception, shutting down");
            this.running.set(false);
         }
      }
      _logger.info("Shutting down task manager.");

      this.taskSet.clear();
      executor.shutdown();
   }
1217970
protected boolean waitForTasks() {
		synchronized (this.tasks) {
			while (!this.closed && !this.hasTaskPending()) {
				try {
					this.tasks.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		return !this.closed;
	}
1088959
private void completedTasklets(final TOutput output, final List<Integer> taskletIds)
      throws InterruptedException {
    final List<TInput> inputs = getInputs(taskletIds);
    final AggregateResult result = new AggregateResult(output, inputs);

    if (callbackHandler != null) {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          callbackHandler.onSuccess(result);
        }
      });
    }

    resultQueue.put(new ImmutablePair<>(taskletIds, result));
  }
209246
def run(self):
    
    while True:
      if self.pool.name:
        self.idle = True

      try:
        # Wait 60 seconds for a message, otherwise exit. This ensures that the
        # threadpool will be trimmed down when load is light.
        task = self._queue.get(timeout=60)

        if self.pool.name:
          self.idle = False

        try:
          # The pool told us to quit, likely because it is stopping.
          if task == STOP_MESSAGE:
            return

          self.ProcessTask(*task)
        finally:
          self._queue.task_done()

      except queue.Empty:
        if self._RemoveFromPool():
          return

      # Try to trim old threads down when they get too old. This helps the
      # thread pool size to shrink, even when it is not idle (e.g. if it is CPU
      # bound) since threads are forced to exit, but new threads will not be
      # created if the utilization is too high - resulting in a reduction of
      # threadpool size under CPU load.
      if time.time() - self.started > 600 and self._RemoveFromPool():
        return
474459
def execute(self):
        
        while self.index < len(self.tasklist):
            res = self.step()
            self.logger.debug('SeqSet task %i has completed with result %s' %
                              (self.index, res))

        # Returns result of last task to quit
        return res
1229218
def run(self):
        """"""
        # Create the thread pool.
        executor = concurrent.futures.ThreadPoolExecutor(
            max_workers=self._config['num_workers'])

        # Wait to ensure multiple senders can be synchronised.
        now = int(datetime.datetime.utcnow().timestamp())
        start_time = ((now + 29) // 30) * 30
        self._log.info('Waiting until {}'.format(
                       datetime.datetime.fromtimestamp(start_time)))
        while int(datetime.datetime.utcnow().timestamp()) < start_time:
            time.sleep(0.1)

        # Run the event loop.
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(self._run_loop(executor))
        except KeyboardInterrupt:
            pass
        finally:
            # Send the end of stream message to each stream.
            self._log.info('Shutting down, closing streams...')
            tasks = []
            for stream, item_group in self._streams:
                tasks.append(stream.async_send_heap(item_group.get_end()))
            loop.run_until_complete(asyncio.gather(*tasks))
            self._log.info('... finished.')
            executor.shutdown()