> 文档中心 > 创建线程的三种方式

创建线程的三种方式


创建线程的三种方式

方法一:实现 Runnable, 接口 实现 run() 方法
方法二:继承 Thread 类, 重写 run() 方法
方法三:使用 lambda 表达式

code demo

import java.util.concurrent.TimeUnit;/** * Created with IntelliJ IDEA. * Description: * * @Author: ZhaoJinlei * DateTime: 2021-08-28 22:53:33 */public class ThreadDemo {    //方法一:实现 Runnable, 接口 实现 run() 方法    static class ThreadA implements Runnable{ @Override public void run() {     for (int i = 0; i < 10; i++) {  System.out.print("ThreadA_  ");  try {      TimeUnit.MICROSECONDS.sleep(1);  } catch (InterruptedException e) {      e.printStackTrace();  }     } }    }    //方法二:继承 Thread 类, 重写 run() 方法    static class ThreadB extends Thread{ @Override public void run() {     for (int i = 0; i < 10; i++) {  System.out.print("ThreadB_ ");  try {      TimeUnit.MICROSECONDS.sleep(1);  } catch (InterruptedException e) {      e.printStackTrace();  }     } }    }    public static void main(String[] args) { //启动线程 A new Thread(new ThreadA()).start(); //启动线程 B new ThreadB().start(); //启动线程 C //方法三:使用 lambda 表达式 new Thread(()->{     for (int i = 0; i < 10; i++) {  System.out.print("ThreadC_ ");  try {      TimeUnit.MICROSECONDS.sleep(1);  } catch (InterruptedException e) {      e.printStackTrace();  }     } }).start(); System.out.println();    }}

开发者涨薪指南 创建线程的三种方式 48位大咖的思考法则、工作方式、逻辑体系