一、可缓存的线程池——newCachedThreadPool
package thread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 该类使用了缓存线程池,体现了线程池重复利用的特点
* 用到的知识点有:匿名内部类只能使用外部被final修饰的变量
* @author Administrator
*
*/
public class Test1 {
public static void main(String[] args) {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
int temp = i;
newCachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName() + ",i:"+ temp);
}
});
}
}
}
总结:线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不是每次创建新线程
二、可固定长度的线程池——newFixedThreadPool
package thread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Administrator
*
*/
public class Test2 {
public static void main(String[] args) {
ExecutorService newCachedThreadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 15; i++) {
int temp = i;
newCachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName() + ",i:"+ temp);
}
});
}
}
}
总结:在指定长度内,线程一直重复利用
三、定时线程池——newScheduledThreadPool
package thread.pool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author Administrator
*
*/
public class Test3 {
public static void main(String[] args) {
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(3);
for (int i = 0; i < 10; i++) {
int temp = i;
newScheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName() + ",i:"+ temp);
}
},3,TimeUnit.SECONDS);
}
}
}
四、单线程的线程池——newSingleThreadExecutor
package thread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Administrator
*
*/
public class Test3 {
public static void main(String[] args) {
ExecutorService newScheduledThreadPool = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
int temp = i;
newScheduledThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName() + ",i:"+ temp);
}
});
}
}
}