首页 > 技术文章 > 使用匿名内部类和lamda的方式创建线程

simpleDi 2019-08-12 16:21 原文

1、匿名内部类的方式

 1 /**
 2  *匿名内部类的方式启动线程
 3  */
 4 public class T2 {
 5     public static void main(String[] args) {
 6      //集成类的方式
 7         new Thread(){
 8             public void run(){
 9                 System.out.println("thread1 start ... ");
10             }
11         }.start();
12  
13      //实现接口的方式
14         new Thread(new Runnable() {
15             @Override
16             public void run() {
17                 System.out.println("thread2 start .... ");
18             }
19         }).start();
20  
21     }
22 }

第1段相当于继承Thread的方式;第二段相当于实现Runnable的方式。

如果我们将上面两段代码合并呢?

 1 package com.yy.concurrent.base1;
 2  
 3 /**
 4  *匿名内部类的方式启动线程
 5  */
 6 public class T2 {
 7     public static void main(String[] args) {
 8  
 9  
10         new Thread(new Runnable() {
11             @Override
12             public void run() {
13                 System.out.println("runnable");
14             }
15         }){
16             public void run(){
17                 System.out.println("sub");
18             }
19         }.start();
20  
21     }
22 }

此时输出sub,此时相当于将一个实现了runnable接口的类对象传入Thread子类的构造方法,并且在这个子类中重写了run方法。因此原本的run()方法被覆盖。

2. Lambda方式

 
public class Test{
    public static void main(String[] args) {
        /*
        匿名内部类的方式
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("nihao");
            }
        }).start();
        System.out.println("你好");
        
        */
        
        
        //lambda的方式
        new Thread(()-> {
            for(int i = 1 ; i<100 ; i++){
                System.out.println("It is a lambda function!");
            }
 
        }).start();
 
    }
}

此时相当于本文第一段代码中的实现接口的方式。

另外可参考:https://blog.csdn.net/Topdandan/article/details/78347865

推荐阅读