Executors 创建线程池
**Executors可以创建不同类型的线程池,先创建一个主线程
public class ThreadForPool implements Runnable {
private Integer index;
public ThreadForPool(Integer index) {
super();
this.index = index;
}
public ThreadForPool() {
super();
}
@Override
public void run() {
System.out.println(“处理线程—-“);
try {
Thread.sleep(index * 1000);
System.out.println(“我的线程标识:” + this.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}**
第一种: 缓存的线程池
**public class TestExecutors {
public static void main(String[] args) {
// 创建可以缓存的线程池
ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i <= 4; i++) {
threadPool.execute(new ThreadForPool(i));
}
}
}**
效果图:
第二种: 定长线程池,可控制并发数
**public class TestExecutors {
public static void main(String[] args) {
// 创建定长线程池,可控制并发数
ExecutorService threadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i <= 4; i++) {
threadPool.execute(new ThreadForPool(i));
}
}
}**
**第三种: 单例线程池
public class TestExecutors {
public static void main(String[] args) {
//单例线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for (int i = 0; i <= 4; i++) {
threadPool.execute(new ThreadForPool(i));
}
}
}**
效果图:
**第四种: 定长线程池,支持定时,周期执行任务
public class TestExecutors {
public static void main(String[] args) {
// 定长线程池,支持定时,周期执行任务
ExecutorService threadPool = Executors.newScheduledThreadPool(3);
for (int i = 0; i <= 4; i++) {
threadPool.execute(new ThreadForPool(i));
}
}
}**