ExecuterService achieve thread pool

Original link: http://www.cnblogs.com/morninglight/p/10339711.html

The role of the thread pool

Limit the number of execution threads in the system

Practice: using a thread pool controls the number of threads, other threads waiting in line.

Why use a thread pool

  • Reducing the creation and destruction of threads
  • The system can adjust the capacity of the number of threads, the system could not carry too much

Several important classes

  • ExecutorService: thread pool Interface
  • ScheduledExecutorService: TimeTask and similar, repetitive tasks performed
  • ThreadPool: the default thread pool implementation
  • ScheduledThreadPoolExecuter: periodic task scheduler implementation class

How to generate the thread pool

Executors class provides factory methods:

  • newSingleThreadExecutor
  • newFixedThreadExecutor
  • newCachedThreadExecutor
  • newScheuledThreadExecutor

For example

Create a fixed-size thread pool

...
    ExecutorService threadPool = Executors.newFixedThreadPool(30);//创建具有30个线程的线程池
    Runnable r1 = new Runable(){
        public void run(){
            //线程体
        }
    };
    threadPool.execute(r1);//将任务交给线程池,其会分配空闲线程来运行这个任务。
    ...

Reproduced in: https: //www.cnblogs.com/morninglight/p/10339711.html

Guess you like

Origin blog.csdn.net/weixin_30746117/article/details/94876911