线程池类似于数据库连接池,创建线程池的具体做法是:先创建多个线程放在线程池中,当有任务需要执行时,从线程池中找一个空闲线程执行任务,任务完成后,并不销毁线程,而是返回线程池,等待新的任务安排。
线程池编程中,任务是提交给整个线程池的,并不是提交给某个具体的线程,而是由线程池从中挑选一个空闲线程来运行任务。一个线程同时只能执行一个任务,可以同时向一个线程池提交多个任务。
一、线程池的使用示例
线程池创建方法:
a、创建一个拥有固定线程数的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
b、创建一个缓存线程池 线程池中的线程数根据任务多少自动增删,动态变化ExecutorService threadPool = Executors.newCacheThreadPool();
c、创建一个只有一个线程的线程池 与单线程一样 但好处是保证池子里有一个线程, 当线程意外死亡,会自动产生一个替补线程,始终有一个线程存活ExecutorService threadPool = Executors.newSingleThreadExector();
往线程池中添加任务threadPool.executor(Runnable);
关闭线程池:threadPool.shutdown(); //线程全部空闲,没有任务就关闭线程池
threadPool.shutdownNow(); //不管任务有没有做完,都关掉
具体代码如下:
package tradition;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 测试线程池
*/
public class ThreadPoolTest {
public static void main(String[] args) {
//创建一个有3个线程的固定线程个数的线程池
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//缓存的线程池,当线程个数不够用时,会自动创建线程
//ExecutorService threadPool = Executors.newCachedThreadPool();
//确保线程池中只有一个线程,好处是即使线程死了,会自动创建一个
//即创建线程时,线程死了会自动创建一个
ExecutorService threadPool = Executors.newSingleThreadExecutor();
//向一个只有1个线程的线程池中放入十个任务
for(int i = 1; i <= 10; i ++) {
final int task = i;
threadPool.execute(new Runnable(){
@Override
public void run() {
for(int j = 1; j <= 10; j ++) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " is looping of " + j
+ " for task " + task);
}
}
});
}
//主线程中的代码
System.out.println("all of 10 tasks hava committed!");
//threadPool.shutdown();//当所有线程完成任务后关闭线程池
//threadPool.shutdownNow();//立刻关闭线程池,即使任务没完成
}
}
二、使用线程池启动定时器
用线程池启动定时器:
a、创建调度线程池,提交任务,延迟指定时间后执行任务
Executors.newScheduledThreadPool(线程数).schedule(Runnable, 延迟时间,时间单位);
b、创建调度线程池,提交任务,延迟指定时间执行任务后,间隔指定时间循环执行
Executors.newScheduledThreadPool(线程数).schedule(Runnable, 延迟时间,
间隔时间,时间单位);
所有的 schedule 方法都接受相对 延迟和周期作为参数,而不是绝对的时间或日期。将以 Date 所表示的绝对时间转换成要求的形式很容易。例如,要安排在某个以后的 Date 运行,可以使用:schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)。
使用线程池启动定时器具体代码:
package tradition;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 使用线程池启动定时器
*/
public class ThreadPoolTimer {
public static void main(String[] args) {
//向定时的线程池中添加定时任务,过10秒后炸
Executors.newScheduledThreadPool(3).schedule(new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}
},
10,
TimeUnit.SECONDS);
//根据固定的频率炸,6秒后炸,在每隔2秒找
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}
},
6,
2,
TimeUnit.SECONDS);
}
}