10、线程生命周期
11、线程池
线程池是预先创建线程的一种技术。线程池在还没有任务到来之前,创建一定数量的线程,放入空闲队列中,然后对这些资源进行复用。减少频繁的创建和销毁对象。jdk1.5版本以上提供了现成的线程池。
Java里面线程池的顶级接口是Executor,是一个执行线程的工具。线程池接口是ExecutorService。
java.util.concurrent 包:并发编程中很常用的实用工具类
Executor 接口:
执行已提交的 Runnable 任务的对象。
ExecutorService 接口:
Executor 提供了管理终止的方法,以及可为跟踪一个或多个异步任务执行状况而生成Future 的方法。
Executors 类:
此包中所定义的Executor、ExecutorService等的工厂和实用方法。
在Executors类里面提供了一些静态工厂,生成一些常用的线程池。
newSingleThreadExecutor:
创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执
行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此
线程池保证所有任务的执行顺序按照任务的提交顺序执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDemo5 {
public static void main(String[] args) {
//创建一个线程池
//创建一个单线程的线程池
ExecutorService es= Executors.newSingleThreadExecutor();
es.execute(new MyRunnable6());
es.execute(new MyRunnable6());
//结束线程
es.shutdown();
}
}
class MyRunnable6 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run--"+i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
newFixedThreadPool:创建固定大小的线程池。每次提交一个任务就创建一个线程,直
到线程达到线程池的最大大小。
线程池的大小一旦达到最大值就会保持不变,
如果某个线程因为执行异常而结束,
那么线程池会补充一个新线程。
public class ThreadDemo5 {
public static void main(String[] args) {
//创建一个线程池
//创建一个单线程的线程池
//ExecutorService es= Executors.newSingleThreadExecutor();
//创建一个固定大小的线程池
ExecutorService es=Executors.newFixedThreadPool(2);
//两个线程同时进行
es.execute(new MyRunnable6());
es.execute(new MyRunnable6());
//结束线程
es.shutdown();
}
}
class MyRunnable6 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"->"+i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
pool-1-thread-1->0
pool-1-thread-2->0
pool-1-thread-2->1
pool-1-thread-1->1
pool-1-thread-1->2
pool-1-thread-2->2
pool-1-thread-1->3
pool-1-thread-2->3
pool-1-thread-1->4
pool-1-thread-2->4
pool-1-thread-1->5
pool-1-thread-2->5
pool-1-thread-2->6
pool-1-thread-1->6
pool-1-thread-1->7
pool-1-thread-2->7
pool-1-thread-2->8
pool-1-thread-1->8
pool-1-thread-1->9
pool-1-thread-2->9
pool-1-thread-2->10
pool-1-thread-1->10
pool-1-thread-1->11
pool-1-thread-2->11
pool-1-thread-1->12
pool-1-thread-2->12
pool-1-thread-1->13
pool-1-thread-2->13
pool-1-thread-1->14
pool-1-thread-2->14
pool-1-thread-2->15
pool-1-thread-1->15
pool-1-thread-1->16
pool-1-thread-2->16
pool-1-thread-1->17
pool-1-thread-2->17
pool-1-thread-1->18
pool-1-thread-2->18
pool-1-thread-2->19
pool-1-thread-1->19
newCachedThreadPool:
创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回
收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加
新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系
统(或者说JVM)能够创建的最大线程大小。
ExecutorService es=Executors.newCachedThreadPool();
newScheduledThreadPool:
创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。
//创建一个大小无限的线程池。
ExecutorService es=Executors.newScheduledThreadPool(3);//大小为3
线程池 最直接的好处就是:线程可以重复利用,减少创建和销毁线程所带来的的系统资源的开销,提升性能(使程序响应更快)