线程池在系统启动时会创建大量的空闲线程,程序将一个Runnable对象传给线程池,线程池就会启动一条线程来执行该对象的run方法,当run方法执行完成,该线程并不是死亡,而是返回线程池中成为空闲线程,等待执行下一个Runnable对象的run方法
创建线程池的一般步骤:
(1)调用executors类的静态工厂方法创建一个executorService对象,该对象就代表了线程池。
(2)创建runnable类或Callable类的实例,作为线程执行任务
(3)调用executorService对象的submit()提交runnable类额实例
(4)调用shutdown()关闭线程池
package test;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
class TestThread implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
class TestThread2 implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public class ThreadPoolTest {
public static void main(String args[]){
//create a threadpool with six fix threads
ExecutorService pool=Executors.newFixedThreadPool(6);
//submit thread to threadpool and execute run()
pool.submit(new TestThread());
pool.submit(new TestThread2());
//close pool
pool.shutdown();
}
}