Java 创建多线程的两种方式 异步执行

实现Runable接口

通过实现Runable接口中的run()方法

public class ThreadTest implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadTest());
        thread.start();
    }

    @Override
    public void run() {
        System.out.println("Runable 方式创建的新线程");
    }
}

继承Thread

通过继承Thread类,重写run()方法,随后实例调用start()方法启动

public class ThreadTest extends Thread{
    @Override
    public void run() {
        System.out.println("Thread 方式创建的线程");
    }

    public static void main(String[] args) {
        new ThreadTest().start();
    }
}

对于第一种方式,其本质就是调用Thread类的构造函数,传入Ruanble接口的实现类

因为Runable接口是一个FunctionalInterface, 因此也可以使用Lambda表达式简写为

public static void main(String[] args) {
      new Thread(() -> {
            System.out.println("新线程");
      }).start();
}

猜你喜欢

转载自www.cnblogs.com/esrevinud/p/13376438.html