实现Runable接口
通过实现Runable接口中的run()方法
1 2 3 4 5 6 7 8 9 10 | 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()方法启动
1 2 3 4 5 6 7 8 9 10 | 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表达式简写为
1 2 3 4 5 | public static void main(String[] args) { new Thread(() -> { System.out.println( "新线程" ); }).start(); } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/191892/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)