首页 > 编程开发 > Java    日期:2020-11-04 / 浏览

实现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();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持免费资源网。

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章