Threads are created only when get_project is called, and terminate
        before it returns. They are there primarily to parallelise I/O (i.e.
        fetching web pages).
425611
def _prepare_threads(self):
        
        self._threads = []
        for i in range(self.num_workers):
            t = threading.Thread(target=self._fetch)
            t.setDaemon(True)
            t.start()
            self._threads.append(t)
1296083
@Beta
  @GwtIncompatible // concurrency
  public static ThreadFactory platformThreadFactory() {
    if (!isAppEngine()) {
      return Executors.defaultThreadFactory();
    }
    try {
      return (ThreadFactory)
          Class.forName("com.google_voltpatches.appengine.api.ThreadManager")
              .getMethod("currentRequestThreadFactory")
              .invoke(null);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e);
    } catch (InvocationTargetException e) {
      throw Throwables.propagate(e.getCause());
    }
  }
612453
IOThread chooseIoThread(long affinity)
    {
        if (ioThreads.isEmpty()) {
            return null;
        }

        //  Find the I/O thread with minimum load.
        int minLoad = -1;
        IOThread selectedIoThread = null;

        for (int i = 0; i != ioThreads.size(); i++) {
            if (affinity == 0 || (affinity & (1L << i)) > 0) {
                int load = ioThreads.get(i).getLoad();
                if (selectedIoThread == null || load < minLoad) {
                    minLoad = load;
                    selectedIoThread = ioThreads.get(i);
                }
            }
        }
        return selectedIoThread;
    }
707742
def with_thread_pool(self, init_func=None, only_read=False):
        
        if not hasattr(self, 'thread_pool') or self.thread_pool is None:
            if init_func is not None:
                self.thread_pool = init_func()
            else:
                self.thread_pool = _init_thread_pool()
            self.enable_thread_pool = True
            self.logger.debug('Initialize thread pool completed %s' % self.thread_pool)
            return True
        else:
            self.logger.warning('Already have a thread pool instance - %s' % self.thread_pool)
            return False
1154772
def _thread(self):
        
        # Get
        args, kwargs = self._jobs.get()

        # Stop thread when (None, None) comes in
        if args is None and kwargs is None:
            return None  # Wrappers should exit as well

        # Work
        try:
            self._results.append(self._worker(*args, **kwargs))
            return True
        except Exception as e:
            self._errors.append(e)
            return False
        finally:
            self._jobs.task_done()
            with self._jobfinished:
                self._jobfinished.notify()
1026156
def _doSelectInThread(self, timeout):
        
        reads = self.reads
        writes = self.writes
        while 1:
            try:
                r, w, ignored = _select(reads.keys(),
                                        writes.keys(),
                                        [], timeout)
                break
            except ValueError, ve:
                # Possibly a file descriptor has gone negative?
                log.err()
                self._preenDescriptorsInThread()
            except TypeError, te:
                # Something *totally* invalid (object w/o fileno, non-integral
                # result) was passed
                log.err()
                self._preenDescriptorsInThread()
            except (select.error, IOError), se:
                # select(2) encountered an error
                if se.args[0] in (0, 2):
                    # windows does this if it got an empty list
                    if (not reads) and (not writes):
                        return
                    else:
                        raise
                elif se.args[0] == EINTR:
                    return
                elif se.args[0] == EBADF:
                    self._preenDescriptorsInThread()
                else:
                    # OK, I really don't know what's going on.  Blow up.
                    raise
        self._sendToMain('Notify', r, w)
1152544
private void stopThreadPool(ExecutorService threadPool) {
        LibraryUtils.checkCondition(threadPool == null, "Thread pool is null when calling stop");

        if (threadPool.isShutdown()) {
            logger.debug(threadPool.toString() + " is already stopped.");

        } else {

            logger.debug(threadPool.toString() + " is about to shutdown.");
            threadPool.shutdown(); // Shutdown thread pool

            try { // Wait for shutdown
                threadPool.awaitTermination(config.getThreadTerminationDelaySeconds(), TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                logger.debug("Wait thread pool termination is interrupted.");
            }

            if (!threadPool.isShutdown()) { // ShutdownNow after waiting
                logger.debug(threadPool.toString() + " is force to shutdown now.");
                threadPool.shutdownNow();
            }

            logger.debug(threadPool.toString() + " is stopped.");
        }
    }
731606
def create_thread(*args)
      return if pool_closed?
      thread = nil
      @lock.synchronize do
        if(args.include?(:nowait) || action_size > size || action_size > waiting || args.include?(:force))
          if(size < max || args.include?(:force))
            thread = ActionPool::Thread.new(:pool => self, :respond_thread => @respond_to,
              :a_timeout => @action_timeout, :t_timeout => @thread_timeout, :logger => @logger,
              :autostart => false)
            @threads << thread
          end
        end
        if(((size == working || args.include?(:nowait)) && @threads.size < @max_threads) || args.include?(:force))

        end
      end
      thread.start if thread
      thread
    end
1267351
private static ThreadFactory createThreadFactory(ThreadFactory threadFactory, String threadNamePrefix,
			Boolean daemon) {
		if (threadFactory != null) {
			return threadFactory;
		}

		if (threadNamePrefix != null) {
			if (daemon != null) {
				return ThreadPoolUtil.buildThreadFactory(threadNamePrefix, daemon);
			} else {
				return ThreadPoolUtil.buildThreadFactory(threadNamePrefix);
			}
		}

		return Executors.defaultThreadFactory();
	}
486271
def _create_inbound_thread(self):
        
        inbound_thread = threading.Thread(target=self._process_incoming_data,
                                          name=__name__)
        inbound_thread.daemon = True
        inbound_thread.start()
        return inbound_thread
1306021
def on_threads_request(self, py_db, request):
        '''
        
        '''
        return self.api.list_threads(py_db, request.seq)
56878
public static void cleanupThreadLocals(Thread thread)
   {
      if (!OperatingSystemUtils.isJava8())
      {
         return;
      }
      try
      {
         if (thread != null)
         {
            cleanField(thread, Thread.class.getDeclaredField("threadLocals"));
            cleanField(thread, Thread.class.getDeclaredField("inheritableThreadLocals"));
         }
      }
      catch (Exception e)
      {
         log.log(Level.WARNING, "Failed to cleanup ThreadLocal instances for Thread [" + thread + "]", e);
      }
   }
481435
private static <T> ThreadContext<T> getCurrentThreadContext(ThreadContext<T> threadContext)
    {
        return ((ThreadContextImpl<T>) threadContext).get();
    }
582887
public ThreadContext getThreadContext() {
        if (useInheritableThreadLocal && !SSLConfigManager.getInstance().isServerProcess()) {
            ThreadContext context = inheritableThreadLocStorage.get();

            if (context == null) {
                context = new ThreadContext();
                inheritableThreadLocStorage.set(context);
            }
            return context;
        }
        ThreadContext context = threadLocStorage.get();

        if (context == null) {
            context = new ThreadContext();
            threadLocStorage.set(context);
        }

        return context;
    }
363450
def default_create_thread(callback):
    
    thread = threading.Thread(None, callback)
    thread.daemon = True  # Don't let thread prevent termination
    thread.start()
    return thread
484216
def get_thread(self):
        
        tid     = self.get_tid()
        process = self.get_process()
        if process.has_thread(tid):
            thread = process.get_thread(tid)
        else:
            # XXX HACK
            # The thread object was missing for some reason, so make a new one.
            thread = Thread(tid)
            process._add_thread(thread)
        return thread
48525
@Override
	protected AsyncTaskProcessorThread createPoolObject() throws Exception
	{
		AsyncTaskProcessorThread thread = new AsyncTaskProcessorThread(listener);
		thread.setName(name);
		thread.start();	
		return thread;
	}