zoukankan      html  css  js  c++  java
  • Java中创建多线程

    Java中创建新线程有多种方式,一般从Thread派生一个自定义类,然后覆写run方法,或者创建Thread实例时,传入一个Runnable实例。两种方式可通过内部匿名类或者lambda语法进行简写。

    1、通常写法

    class MyTheard extends Thread {
        @Override
        public void run() {
            System.out.println("new thread created by extends thread");
        }
    }
    
    class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("new thread created by implements runnable");
        }
    }
    Thread t1 = new MyTheard();
    Thread r1 = new Thread(new MyRunnable());
    t1.start();
    r1.start();

    2、使用内部匿名类简写

    Thread t2 = new Thread() {
        @Override
        public void run() {
            System.out.println("new thread created by extends thread using Anonymous class");
        }
    };
    
    Runnable r2 = new Runnable() {
        @Override
        public void run() {
            System.out.println("new thread created by implements runnable using Anonymous class");
        }
    };
    t2.start();
    new Thread(r2).start();

    3、使用lambda语法

    Thread t3 = new Thread(()-> {
        System.out.println("new thread created by extends thread using lambda");
    });
    
    Runnable r3 = ()-> {
        System.out.println("new thread created by implements runnable using lambda");
    };
    t3.start();
    new Thread(t3).start();

     使用简化的语法,减少了代码量,并且无需定义子类名,解决了命名难的问题。

    参考链接

    https://www.liaoxuefeng.com/wiki/1252599548343744/1376414781669409

  • 相关阅读:
    LCA+链式前向星模板
    truffle编译合约常见问题及其在私链上的部署与交互
    RMQ入门解析
    最短路_搜索
    无向图边双联通分量+缩点
    有向图+强联通分量
    染色法判二分
    邻接表存图
    贪心算法
    贪心算法
  • 原文地址:https://www.cnblogs.com/engeng/p/15538830.html
Copyright © 2011-2022 走看看