20231101_210520 java 线程池 认识线程池 体验线程池
线程池原理
常用线程池的接口与类
限定个数的线程池
输出结果中只会看到线程1到线程4
package test2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
// 具有4个线程个数的线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
// 定义一个规则对象
Runnable runnable = new Runnable() {
@Override
public void run() {
int ticket = 100;
while (true) {
if (ticket <= 0) {
break;
}
String fmt = "%s卖了第%s张票";
String msg = String.format(fmt, Thread.currentThread().getName(), ticket);
System.out.println(msg);
ticket--;
}
}
};
// 线程池提交六个任务
for (int i = 0; i < 6; i++) {
executorService.submit(runnable);
}
// 结束线程
executorService.shutdown();
}
}
缓存线程池
线程个数与任务数有关
本例可以看到有六个线程
package test2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
// 创建缓存线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 定义一个规则对象
Runnable runnable = new Runnable() {
@Override
public void run() {
int ticket = 100;
while (true) {
if (ticket <= 0) {
break;
}
String fmt = "%s卖了第%s张票";
String msg = String.format(fmt, Thread.currentThread().getName(), ticket);
System.out.println(msg);
ticket--;
}
}
};
// 线程池提交六个任务
for (int i = 0; i < 6; i++) {
executorService.submit(runnable);
}
// 结束线程
executorService.shutdown();
}
}