1.newFixedThreadPool:固定长度的线程池,每提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程规模将不再变化。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolPrac {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
public void run() {
try {
System.out.print("当前线程"+index);
System.out.print("当前活跃线程池大小:"+Thread.activeCount());
System.out.println();
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch blocke.printStackTrace();
}
}
});
}
fixedThreadPool.shutdown();
}
}
2.newCachedThreadPool:一个可缓存的线程池,线程池的规模超过了处理需求,将自动回收空闲线程,当需求增加时,可以添加新线程,线程池的规模不存在任何限制,没有顺序执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPoolPrac {
public static void main(String[] args){
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for(int i=0 ; i<10; i++){
final int index = i;
try {
Thread.sleep(index*1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
cachedThreadPool.execute(new Runnable(){
public void run() {
try{
System.out.print("当前线程"+index);
System.out.print("当前活跃线程池大小:"+Thread.activeCount());
System.out.println();
}catch (Exception e) {
// TODO: handle exception
}
}
});
}
cachedThreadPool.shutdown();
}
}
3.newScheduledThreadPool :创建一个固定长度的线程池,而且以延迟或定时的方式来执行任务。创建一个定长线程池,支持定时及周期性任务执行。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolPrac {
public static void main(String[] args) {
final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
/*scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
}*/
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
int i = 0;
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
System.out.println("当前活跃线程池"+Thread.activeCount());
if(i>5){
scheduledThreadPool.shutdown();
}else{
i++;
}
}
}, 1, 3, TimeUnit.SECONDS);}
}
4.newSingleThreadExecutor:单个工作线程来执行任务,如果这个线程异常结束,就会有一个新的来替代它,它的特点是能确保任务在队列中的顺序来串行执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadPoolPrac {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
singleThreadExecutor.shutdown();
}
}