启动一个新线程,成本是比较高的,因为需要与操作系统进行交互。
而使用线程池可以很好地提高性能,尤其当需要创建大量生存期很短的线程时,更应该考虑使用线程池。
线程池里的每一条线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下次被调用。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Administrator on 2018/10/21 16:26 in Beijing.
*/
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.submit(new ThreadPoolRunnable());
pool.submit(new ThreadPoolRunnable());
pool.submit(new ThreadPoolRunnable());
pool.shutdown(); // 此时线程池才会关闭
}
}
class ThreadPoolRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
}
}
输出如下
pool-1-thread-2 0
pool-1-thread-3 0
pool-1-thread-1 0
pool-1-thread-3 1
pool-1-thread-2 1
pool-1-thread-3 2
pool-1-thread-1 1
pool-1-thread-1 2
pool-1-thread-3 3
pool-1-thread-2 2
pool-1-thread-3 4
pool-1-thread-3 5
pool-1-thread-3 6
pool-1-thread-3 7
pool-1-thread-3 8
pool-1-thread-1 3
pool-1-thread-1 4
pool-1-thread-1 5
pool-1-thread-1 6
pool-1-thread-3 9
pool-1-thread-2 3
pool-1-thread-2 4
pool-1-thread-2 5
pool-1-thread-2 6
pool-1-thread-2 7
pool-1-thread-2 8
pool-1-thread-1 7
pool-1-thread-2 9
pool-1-thread-1 8
pool-1-thread-1 9
Process finished with exit code 0
注意: 如果 没有最后一行,那么程序并不会退出。
pool.shutdown(); // 此时线程池才会关闭