JAVA中线程池和Lambda表达式

线程池的概念

线程池: 其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。

线程池的创建

在 java.util.concurrent.Executors 线程工厂类里面提供了一些静态工厂,生成一些常用的线程池。

  • public static ExecutorService newFixedThreadPool(int nThreads):返回线程池对象。(创建的是有界线程池,也就是池中的线程个数可以指定最大数量)
  • public Future<?> submit(Runnable task) :获取线程池中的某一个线程对象,并执行



使用线程池中线程对象的步骤:

  1. 创建线程池对象
  2. 创建Runnable接口子类对象
  3. 提交Runnable接口子类对象
  4. 关闭线程池(一般不做)。

案例

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值