1.线程池的核心参数
2.Java之创建线程池的四种方式
package threadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FourWaysToCreateThreadPool {
public static ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
public static ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
public static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
public static void main(String[] args) {
System.out.println("创建线程的四种方式如下");
createNewCachedThreadPool();
createNewFixedThreadPool();
createNewSingleThreadPool();
createNewScheduledThreadPool();
}
public static void createNewCachedThreadPool(){
System.out.println("1.使用newCachedThreadPool-可缓存线程池");
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cacheThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
}
});
}
}
public static void createNewFixedThreadPool(){
System.out.println("2.newFixedThreadPool 指定工作线程数量的线程池");
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
public static void createNewSingleThreadPool(){
System.out.println("3.newSingleThreadPool 只创建唯一的工作线程来执行任务");
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
}
});
}
}
public static void createNewScheduledThreadPool(){
System.out.println("4.newScheduledThreadPool 创建一个定长的线程池,而且支持定时");
scheduledThreadPool.scheduleAtFixedRate(()->{
System.out.println("index");
},1,3, TimeUnit.SECONDS);
}
}