實現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://www.cnblogs.com/esrevinud/p/13376438.html