public function runThreads($maximumConcurrency = 10, $waitForCompletion = false) {

        $remainingThreads = $this->threads;
        $activeThreads = array();

        do {

            // Check to see if threads have completed and remove these.
            foreach ($activeThreads as $pid => $thread) {
                if ($thread->getStatus() == Thread::THREAD_EXITED)
                    unset($activeThreads[$pid]);
            }


            // Start as many threads as we can.
            if ((sizeof($remainingThreads) > 0) && (sizeof($activeThreads) <= $maximumConcurrency)) {

                while ((sizeof($activeThreads) <= $maximumConcurrency) && (sizeof($remainingThreads) > 0)) {


                    $thread = array_shift($remainingThreads);
                    $pid = $thread->run();

                    // Store the pid
                    $activeThreads[$pid] = $thread;

                }
            }


            // If we have started the last thread and we are not waiting for completion,
            // exit this loop
            if (sizeof($remainingThreads) == 0 && !$waitForCompletion) {
                break;
            }


            // Wait a second before looping to avoid thrashing.
            sleep(1);


        } while (sizeof($activeThreads) > 0);


    }