1)和3)和消耗都是很大的。甚至有可能会超过2),即创建线程和销毁线程会消耗很多资源的。
Java里面线程池有哪些创建方式呢?
①借助Concurrent里的一个类 Executors(这个类的对象有好几种创建方式)
- Executors.newSingleThreadExecutor();
- Executors.newFixedThreadPool(2);
- Executors.newCachedThreadPool();//推荐使用,在你需要的时候可以给你智能地添加新的线程,不用的时候可以给你缩小,回收。是可以缓存的那么一个线程池
- Executors.newScheduledThreadPool(3) 调度的 创建一个能调度的线程池,基于你给定的delay,实现一个周期性的调度
/**
* Creates an Executor that uses a single worker thread operating
创建使用单个工作线程操作的执行器
* off an unbounded queue, and uses the provided ThreadFactory to
* create a new thread when needed. Unlike the otherwise
* equivalent {@code newFixedThreadPool(1, threadFactory)} the
* returned executor is guaranteed not to be reconfigurable to use
* additional threads.
*
* @param threadFactory the factory to use when creating new
* threads
*
* @return the newly created single-threaded Executor
* @throws NullPointerException if threadFactory is null
*/
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)
/**
* 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() {
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @param threadFactory the factory to use when the executor
* creates a new thread
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
* @throws NullPointerException if threadFactory is null
*/
public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory)
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
Thread t1 = new LZTread();
Thread t2 = new LZTread();
Thread t3 = new LZTread();
Thread t4 = new LZTread();
Thread t5 = new LZTread();
//把他们放到线程池里面执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.shutdown();
}
}
public class LZTread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ".......");
}
}