CachedThreadPool线程池的使用

简介 :这个线程池默认最大数:0x7fffffff,当在线程池中建立一个线程后,60秒内如果没有再次使用编号自动销毁这个线程,如果60秒内再次用到改线程那么边会从线程池中将这个线程唤醒,不会重新建立一个线程。

  /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to {@code execute} will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

导包

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

声明

public static ExecutorService mythread = Executors.newCachedThreadPool();

使用

mythread.execute(new Runnable() {
                    public void run() {
                       /*执行代码*/
                       }
                });

你可能感兴趣的:(线程)