zoukankan      html  css  js  c++  java
  • 使用匿名内部类和lamda的方式创建线程

    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

  • 相关阅读:
    Java中的LinkedList
    Java中的List集合
    Java中的集合Collection
    Java中的异常
    mvc+EF实现简单的登陆功能
    ASP.NET MVC学习三-数据传递之模型绑定
    ASP.NET MVC学习二之 Controller
    ASP.NET MVC 学习一之路由
    ASP.NET MVC学习
    winform获取网页代码的两种方式:
  • 原文地址:https://www.cnblogs.com/simpleDi/p/11340876.html
Copyright © 2011-2022 走看看