方法1:Java自带的线程池

采用Executors的factory method创建了固定大小的线程池,采用execute()方法添加Runnable Task。

1 ExecutorService threadPool = Executors.newFixedThreadPool(2);
2 for (int i = 0; i < 4; i++)
3      threadPool.execute(new InnerWork(i + ""));
4 threadPool.shutdown();

内部实现是采用LinkedBlockingQueue。

/**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * <tt>nThreads</tt> threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if <tt>nThreads &lt;= 0</tt>
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-06-07
  • 2022-02-12
  • 2021-06-15
  • 2021-11-20
  • 2022-01-06
  • 2022-03-01
  • 2021-03-31
猜你喜欢
  • 2022-02-22
  • 2021-08-30
  • 2023-04-11
  • 2021-10-21
  • 2021-12-06
  • 2021-10-31
相关资源
相似解决方案