thread pool and lambda expressions
Learn the understanding of thread pools and lambda expressions
Add a point of knowledge (Singleton design mode)
In multi-threaded, we only need a task class, in order to prevent the creation of more than one task class, this time need to use the singleton mode, the singleton mode has two kinds of design:
- Lazy loading (lazy type)
- Private construction methods
- Creates this class object, but does not initialize
- Creates a static method to initialize the object and returns
- Load now (a Hungry man type)
- Private construction methods
- Create objects of this class and initialize (private)
- Create a static method to get this class of objects
Here's an example of code:
Package com.wzlove.single;/** * Lazy load (lazy) * 1. Private construction Method * 2. Create this class object, but do not initialize * 3. Create a static method to initialize the object and return the * Advantage: * Objects that are used to classes are loaded, No memory consumption * Disadvantages: * Thread safety issues may occur, but you can use synchronized blocks to eliminate this security issue * @author Wzlove * @create 2018-07-19 10:36 */public class Deplayedsin GLE {//Private constructor Deplayedsingle () {}///Create this class object, do not initialize private static deplayedsingle instance; static method initializes public static Deplayedsingle getinstance () {synchronized (Deplayedsingle.class) {if (Instan CE = = null) {instance = new Deplayedsingle (); }} return instance; }}package com.wzlove.single;/** * Immediate load (a hungry man type) * 1. Private construction Method * 2. Create objects of this class and initialize (private) * 3. Create a static method to get this class of objects * * Advantages: * Guaranteed thread security, no Thread safety issues * Cons: * Use class will load, compare memory consumption * @author Wzlove * @create 2018-07-19 10:37 */public class Immediatesingle {Priva Te Immediatesingle () {} private static Immediatesingle instance = new Immediatesingle (); public static Immediatesingle getinstance () {return instance; }}
Thread Pool Overview
The thread pool is actually a container that accommodates multiple threads, where threads can be reused, eliminating the frequent creation of thread objects.
There is no need to repeatedly create threads and consume too many resources. The function is to save resources, the principle is the container.
The benefit of using the thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources to solve the problem of insufficient resources. If you do not use a thread pool,
It is possible to cause the system to create a large number of similar threads that can consume memory or "over-switch" issues.
To create a thread pool:
- public static Executorservice newfixedthreadpool (int nthreads): Returns the thread pool object. (created with a line
Pool, that is, the number of threads in the pools can specify the maximum number)
- Public future<?> Submit (Runnable Task): Gets a thread object in the thread pool and executes
- Future interface: Used to record the results of a thread task after it has been executed. Thread pool creation and use.
Steps:
- Factory class using the thread pool executors provides a static method newfixedthreadpool a thread pool that produces a specified number of threads
- Create a class that implements the Runnable interface, overrides the Run method, sets the thread task
- Call the method in Executorservice, pass the thread task (implementation Class), open the thread (provided the thread pool is available), execute the Run method
- Call the Shutdown method in Executorservice to destroy the thread pool (not recommended)
Creation of supplemental Threads
The third way to create a thread (rarely seen in this way)
Package Com.wzlove.executor;import Java.util.arraylist;import java.util.concurrent.callable;/** * Third Way to create threads * Callable has a return value and can throw an exception * @author wzlove * @create 2018-07-18 14:14 */public class Callableimpl implements Callable<string > {private static arraylist<string> ArrayList = new arraylist<> (); static{Arraylist.add ("1"); @Override public String Call () throws Exception {return Thread.CurrentThread (). GetName (); }}package Com.wzlove.executor;import java.util.concurrent.*;/** * The Third way to create a test thread * * @author wzlove * @create 2018-07-18 14: */public class Demo {public static void main (string[] args) {//Create an implementation class object that implements callable Callable<strin g> callable = new Callableimpl (); Create Futuretask, and pass the implementation class object of the callable interface Futuretask task = new Futuretask (callable); Create thread pool object//Executorservice executor = Executors.newsinglethreadexecutor (); Executorservice executor = Executors.newfixedthreadpool (3); Executor.submit (callable); Execution thread Executor.execute (Task); try {System.out.println (Task.get ()); } catch (Interruptedexception e) {e.printstacktrace (); } catch (Executionexception e) {e.printstacktrace (); } }}
Lambda expression
Lambda embodies the idea of functional programming, which emphasizes what to do, not what form.
Usage Prerequisites
- Using a lambda must have an interface and require that there is only one abstract method in the interface. Whether the runnable, Comparator interface, or custom interface is built into the JDK, lambda can only be used if the abstract method in the interface exists and is unique.
- Using lambda must have context inference. That is, the method's parameter or local variable type must be a lambda-corresponding interface type to use lambda as an instance of the interface.
An interface that has and has only one abstract method, called a "functional interface."
Lambda standard format
Lambda omits object-oriented rules, and the format consists of 3 parts:
- Some parameters
- An arrow
- A section of code
The standard format for lambda expressions is:
(参数类型 参数名称) ‐> { 代码语句 }
Format Description:
- The syntax in parentheses is consistent with the traditional method parameter list: No arguments are left blank, and multiple parameters are separated by commas.
- is the newly introduced syntax format, which represents the pointing action.
- The syntax in curly braces is basically consistent with the traditional method body requirements.
Conversion of Thread Anonymous inner class (no parameter, no return value)
Implementation of an anonymous inner class that implements the Runnable interface:
public class Demo01Runnable { public static void main(String[] args) { // 匿名内部类 Runnable task = new Runnable() { @Override public void run() { // 覆盖重写抽象方法 System.out.println("多线程任务执行!"); } }; new Thread(task).start(); // 启动线程 }}
Code Analysis
- The thread class requires the Runnable interface as a parameter, where the abstract run method is used to specify the core of the thread's task content;
- In order to specify the method body of the run, the implementation class of the Runnable interface is required;
- To eliminate the hassle of defining a Runnableimpl implementation class, you have to use anonymous internal classes;
- The override abstract run method must be overridden, so the method name, method parameter, method return value have to be written again, and cannot be written incorrectly;
- In fact, it seems that only the method body is the key.
Use lambda for simplification:
public class Demo01Runnable { public static void main(String[] args) { new Thread(()->System.out.println("多线程任务执行!")).start(); // 启动线程 }}
Conversion of classes within the comparator (with parameter return values)
Use the comparator for an example:
// 创建数组Integer[] arr = {1,8,3,4,9,2,5};// 匿名内部类实现数组升序排序Arrays.sort(arr,new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { return 0; }});// 使用lambda进行数组的升序排序Arrays.sort(arr,( a, b)->{ return a - b ;});
Ellipsis rules for lambda expressions
On the basis of the lambda standard format, the rules for using ellipsis are:
- The type of the parameters within the parentheses can be omitted;
- If there is only one parameter in the parentheses, the parentheses can be omitted;
- If there is only one statement inside the curly brace, you can omit the curly brace, the return keyword, and the statement semicolon, regardless of the return value.
Although there is an ellipsis, but I feel that this is a bit flexible, so it is not recommended to omit, because the code is for others to see, omit the words feel that others seem to be a bit laborious.
Java thread pool and lambda expressions