雖然可以通過Thread類的繼承來實現多線程的定義,但是在Java程序裏面對於繼承永遠都是存在有單繼承侷限的,所以在Java裏面有提供有第二種多線程的主體定義結構形式:實現java.lang.Runnable接口,此接口定義如下:
@FunctionalInterface //從JDK1.8引入了Lambda表達式之後就變成了函數式接口
public interface Runnable{
public void run();
}
例:通過Runnable實現多線程的主體類
class MyThread implements Runnable { //線程的主體類
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() { //線程的主體方法
for (int i = 0; i < 10; i++) {
System.out.println(this.title + "運行,X = " + i);
}
}
}
但是此時由於不再繼承Thread父類了,那麼對於此時MyThread類中也就不不再支持有start()這個繼承的方法,可是如果不使用Thread.start()方法是無法進行多線程啓動的,那麼這個時候就需要去觀察一下Thread類所提供的構造方法:
·構造方法:public Thread(Runnable target);
例:啓動多線程
public class ThreadDemo {
public static void main(String[] args) {
Thread threadA = new Thread( new MyThread("線程A"));
Thread threadB = new Thread( new MyThread("線程B"));
Thread threadC = new Thread( new MyThread("線程C"));
threadA.start(); //啓動多線程
threadB.start(); //啓動多線程
threadC.start(); //啓動多線程
}
}
這個時候的多線程實現裏面可以發現,由於只是實現了Runnable接口對象,所以此時線程主體類就不再有單程侷限了,那麼這樣的設計纔是一個標準型的設計。
可以發現從JDK1.8開始,Runnable接口使用了函數式接口定義,所以也可以直接利用Lambda表達式進行線程類實現。
例:利用Lambda實現多線程定義
public class ThreadDemo {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
String title = "線程對象-" + i;
new Thread(()->{
for (int j = 0; j < 10; j++) {
System.out.println(title + "運行,j = " + j);
}
}).start();
}
}
}
在以後的開發之中對於多線程的實現,優先考慮的就是Runnable接口實現,並且永恆都是通過Thread類對象啓動多線程。