JAVA thread pool, Lambda expression notes, examples and precautions

1 thread pool

Thread pool : In fact, it is a container that holds multiple threads. The threads can be used repeatedly, eliminating the need for frequent object creation operations, and there is no need to repeatedly create threads and consume too much resources.
Reasonable use of thread pool can bring three benefits:
1. Reduce resource consumption. The number of times of creating and destroying threads is reduced, and each thread can be reused to perform multiple tasks.
2. Improve response speed. When the task arrives, the task can be executed immediately without waiting for the thread to be created.
3. Improve the manageability of threads. You can adjust the number of worker threads in the thread pool according to the system's affordability to prevent the server from consuming too much memory (each thread requires about 1MB of memory, the more threads are opened, the more memory is consumed Big, finally crashed).

/*
    线程池:JDK1.5之后提供的
    java.util.concurrent.Executors:线程池的工厂类,用来生成线程池
    Executors类中的静态方法:
        static ExecutorService newFixedThreadPool(int nThreads) 创建一个可重用固定线程数的线程池
        参数:
            int nThreads:创建线程池中包含的线程数量
        返回值:
            ExecutorService接口,返回的是ExecutorService接口的实现类对象,我们可以使用ExecutorService接口接收(面向接口编程)
    java.util.concurrent.ExecutorService:线程池接口
        用来从线程池中获取线程,调用start方法,执行线程任务
            submit(Runnable task) 提交一个 Runnable 任务用于执行
        关闭/销毁线程池的方法
            void shutdown()
    线程池的使用步骤:
        1.使用线程池的工厂类Executors里边提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池
        2.创建一个类,实现Runnable接口,重写run方法,设置线程任务
        3.调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法
        4.调用ExecutorService中的方法shutdown销毁线程池(不建议执行)
 */

2 Standard format of Lambda expression

 /*
    Lambda表达式的标准格式:
        由三部分组成:
            a.一些参数
            b.一个箭头
            c.一段代码
        格式:
            (参数列表) -> {一些重写方法的代码};
        解释说明格式:
            ():接口中抽象方法的参数列表,没有参数,就空着;有参数就写出参数,多个参数使用逗号分隔
            ->:传递的意思,把参数传递给方法体{}
            {}:重写接口的抽象方法的方法体
 */

3 Examples of Lambda expressions with no parameters and no return value

 /*
    定一个厨子Cook接口,内含唯一的抽象方法makeFood
 */
public interface Cook {
    
    
    //定义无参数无返回值的方法makeFood
    public abstract void makeFood();
}
/*
    需求:
        给定一个厨子Cook接口,内含唯一的抽象方法makeFood,且无参数、无返回值。
        使用Lambda的标准格式调用invokeCook方法,打印输出“吃饭啦!”字样
 */
public class Demo01Cook {
    
    
    public static void main(String[] args) {
    
    
        //调用invokeCook方法,参数是Cook接口,传递Cook接口的匿名内部类对象
        invokeCook(new Cook() {
    
    
            @Override
            public void makeFood() {
    
    
                System.out.println("吃饭了");
            }
        });

        //使用Lambda表达式,简化匿名内部类的书写
        invokeCook(()->{
    
    
            System.out.println("吃饭了");
        });

        //优化省略Lambda
        invokeCook(()-> System.out.println("吃饭了"));
    }

    //定义一个方法,参数传递Cook接口,方法内部调用Cook接口中的方法makeFood
    public static void invokeCook(Cook cook){
    
    
        cook.makeFood();
    }
}

4 Lambda expressions have parameters and return values

public class Person {
    
    
    private String name;
    private int age;

    public Person() {
    
    
    }

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}
/*
    Lambda表达式有参数有返回值的练习
    需求:
        使用数组存储多个Person对象
        对数组中的Person对象使用Arrays的sort方法通过年龄进行升序排序
 */
public class Demo01Arrays {
    
    
    public static void main(String[] args) {
    
    
        //使用数组存储多个Person对象
        Person[] arr = {
    
    
                new Person("柳岩",38),
                new Person("迪丽热巴",18),
                new Person("古力娜扎",19)
        };

        //对数组中的Person对象使用Arrays的sort方法通过年龄进行升序(前边-后边)排序
        /*Arrays.sort(arr, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getAge()-o2.getAge();
            }
        });*/

        //使用Lambda表达式,简化匿名内部类
        Arrays.sort(arr,(Person o1, Person o2)->{
    
    
            return o1.getAge()-o2.getAge();
        });

        //优化省略Lambda
        Arrays.sort(arr,(o1, o2)->o1.getAge()-o2.getAge());

        //遍历数组
        for (Person p : arr) {
    
    
            System.out.println(p);
        }
    }
}

5 Lambda expressions have parameters and return values

/*
    给定一个计算器Calculator接口,内含抽象方法calc可以将两个int数字相加得到和值
 */
public interface Calculator {
    
    
    //定义一个计算两个int整数和的方法并返回结果
    public abstract int calc(int a,int b);
}
/*
    Lambda表达式有参数有返回值的练习
    需求:
        给定一个计算器Calculator接口,内含抽象方法calc可以将两个int数字相加得到和值
        使用Lambda的标准格式调用invokeCalc方法,完成120和130的相加计算
 */
public class Demo01Calculator {
    
    
    public static void main(String[] args) {
    
    
        //调用invokeCalc方法,方法的参数是一个接口,可以使用匿名内部类
        invokeCalc(10, 20, new Calculator() {
    
    
            @Override
            public int calc(int a, int b) {
    
    
                return a+b;
            }
        });

        //使用Lambda表达式简化匿名内部类的书写
        invokeCalc(120,130,(int a,int b)->{
    
    
            return a + b;
        });

        //优化省略Lambda
        invokeCalc(120,130,(a,b)-> a + b);
    }

    /*
        定义一个方法
        参数传递两个int类型的整数
        参数传递Calculator接口
        方法内部调用Calculator中的方法calc计算两个整数的和
     */
    public static void invokeCalc(int a,int b,Calculator c){
    
    
        int sum = c.calc(a,b);
        System.out.println(sum);
    }
}

6 Lambda expression considerations

/*
Lambda表达式:是可推导,可以省略
  凡是根据上下文推导出来的内容,都可以省略书写
可以省略的内容:
1.(参数列表):括号中参数列表的数据类型,可以省略不写
2.(参数列表):括号中的参数如果只有一个,那么类型和()都可以省略
3.{一些代码}:如果{}中的代码只有一行,无论是否有返回值,都可以省略({},return,分号)
注意:要省略{},return,分号必须一起省略
 */

Guess you like

Origin blog.csdn.net/TOPic666/article/details/107914483