线程池的概念
线程池: 其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。
线程池的创建
在 java.util.concurrent.Executors 线程工厂类里面提供了一些静态工厂,生成一些常用的线程池。
- public static ExecutorService newFixedThreadPool(int nThreads):返回线程池对象。(创建的是有界线程池,也就是池中的线程个数可以指定最大数量)
- public Future<?> submit(Runnable task) :获取线程池中的某一个线程对象,并执行
使用线程池中线程对象的步骤:
- 创建线程池对象
- 创建Runnable接口子类对象
- 提交Runnable接口子类对象
- 关闭线程池(一般不做)。
案例
public class MyThread implements Runnable{
@Override
public void run() {
System.out.println("线程执行了");
}
}
public class Main {
public static void main(String[] args) {
//创建容量为3的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
MyThread thread = new MyThread();
//分配线程执行run方法
threadPool.submit(thread);
//关闭线程池
threadPool.shutdown();
}
}
结果
线程执行了
Lambda表达式
Lambda省去面向对象的条条框框,格式由3个部分组成:
- 一些参数
- 一个箭头
- 一段代码
Lambda表达式的标准格式为:
(参数类型 参数名称) ‐> { 代码语句 }
使用条件: 接口中有且只能有一个抽象方法
实现Runnable接口传统写法
public class Main {
public static void main(String[] args) {
// 匿名内部类
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("线程执行了");
}
};
// 启动线程
new Thread(runnable).start();
}
}
Lambda表达式写法
public class Main {
public static void main(String[] args) {
new Thread(()-> System.out.println("线程执行了")).start();
}
}
练习
无参无返回值
interface Person{
void eat();
}
public class Main {
public static void main(String[] args) {
testPerson(()-> System.out.println("吃零食了"));
}
public static void testPerson(Person person){
person.eat();
}
}
有参有返回值
interface Calculator{
int sum(int a,int b);
}
public class Main {
public static void main(String[] args) {
test((a,b)->a+b);
}
public static void test(Calculator calculator){
int sum = calculator.sum(1, 2);
System.out.println(sum);
}
}