线程池:
* 特点:
* 线程池:产生一个固定的可重用的线程数,线程对象创建完毕并且执行完毕,不会被
* GC回收掉,而是将该线程对象再次归还到线程池中,等待下次重复利用
* 数据库来连接池:产生一个固定的可用的连接连接池,记录最大的链接数量是多少个
* 记录最小的链接数是多少个,一旦超出了最大连接数量,将这里面某个连接对象colse()掉
* 归还到连接池中!
* 无论线程池还是连接池弊端:
* 使用成本要比传统的开启线程成本大
* ExecutorService:接口 线程池:如何实例化
* 不能直接实例化,所以提供工程类Executors
*
* 创建固定的可重用的线程数的线程池
* public static ExecutorService newFixedThreadPool(int nThreads)
*
* ExecutorService API
* 提交异步任务
*
* Callable:异步任务接口:
* 有一个抽象方法:V call() throws Exception:具体计算结果
* Future> submit(Runnable task)
*
* void shutdown():将之前提交的异步任务按照顺序关闭
public class ThreadDemo {
public static void main(String[] args) {
//1)创建线程池对象
ExecutorService threadPool=Executors.newFixedThreadPool(2);//线程池中有两个线程
//2)使用线程池提交异步任务:2个(一个异步任务就是一个线程)
threadPool.submit(new MyRunnable());
threadPool.submit(new MyRunnable());
//3)关闭线程池中的异步任务
threadPool.shutdown();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
for(int x=0;x<100;x++) {
System.out.println(Thread.currentThread().getName());
}
}
}



