Lambad expression

  1. Runnable good-bad.
  2. Lambda written in comparison with other writing (160dd5c670a2fe key ).

Lambda expression:

Lambda is an anonymous function, Lambda is a code that can introduce and be more flexible . It was Java8 (note the version).


Runnable code

Normally everyone has to start a thread. Do you have java.lang.Runnable interface, and then use the java.lang.Thread class to start the thread. (Yes, I tried it!)

//匿名内部类写法
public class Demo02{
  public static void main(String []args){
   //    匿名内部类
      Runnable tack  = new Runnable(){
          // 重写run 方法
          @Override
          public void run(){ 
              System.out.println("多线程启动对象");
          }
      };

//      隐名线程 搭配 start
      new Thread(tack).start();

};
 

   }
}

code analysis

Runnable anonymous internal class writing can analyze several contents:

​ 1.Thread requires Runnable interface as a parameter, and the abstract run method is the core of the thread task content.

​ 2. In order to run method body, to need Runnable interface implementation class. And must cover run method, all names, parameters, method return value, to rewritten again 160dd5c670af93

​ 3. In order to save the trouble of RunnableImpl to use an anonymous internal for

Summary: It seems that the method body is the key. So we have to export a better way to write Lambda


Lambda is better written

Lambda is better written
With the new grammar of Java 8, the Runnable interface can be expressed by simpler Lambda expressions.


Standard syntax:

(parameter type parameter name) -> {code statement}

x () -> System.out.println("Multi-threaded task execution!")


How to use Lambda

//     Lambda 表达式使用方法
      new Thread(() -> System.out.println("Lambda表达式")).start();

嘻嘻硕
27 声望12 粉丝

想当一只天然呆的鸭qwq