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