Java多線程:基於Runnable接口實現多線程

雖然可以通過Thread類的繼承來實現多線程的定義,但是在Java程序裏面對於繼承永遠都是存在單繼承侷限的,所以在Java裏面又提供有第二種多線程的主體定義結構形式:實現java.lang.Runnable接口,此接口定義如下:

@FunctionalInterface
public interface Runnable{
	public void run();
}

範例:通過Runnable實現多線程的主體類

由於只是實現了Runnable接口對象,所以此時線程主題類上就不再又單繼承侷限了,那麼這樣的設計纔是一個標準型的設計。

class MyThread implements Runnable{	// 線程的主體類
	private String title;
	public MyThread(String title) {
		this.title = title;
	}
	@Override
	public void run() {	// 多線程要執行的功能應該在run()方法中進行定義
		for(int i = 0; i < 3; i++) {
			System.out.println(this.title + "運行:= " + i);
		}
	}
}

public class Main {

	public static void main(String[] args) {
//		new MyThread("線程A").start();
//		new MyThread("線程B").start();
//		new MyThread("線程C").start();
		
		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();
	}
}

注意:沒有繼承Thread類不能使用start()方法,但是Thread類的構造函數允許接受Runnable的對象,所以實現Runnable的子類對象也可以被Thread類接收

從JDK1.8開始,Runnable接口使用了函數式的接口定義,所以也可以直接利用Lambda表達式進行線程類的實現。

範例:利用Lambda實現多線程的定義

public class Main {

	public static void main(String[] args) {

		for(int i = 0; i < 3; i++) {
			String title = "線程對象-" + i;
			Runnable run = ()->{
				for(int j = 0; j < 5; j++) {
					System.out.println(title + "運行, j = " + j);
				}
			};
			new Thread(run).start();
		}
  
          		// 形式二
//		for(int i = 0; i < 3; i++) {
//			String title = "線程對象-" + i;
//			new Thread ( ()->{
//				for(int j = 0; j < 5; j++) {
//					System.out.println(title + "運行, j = " + j);
//				}
//			}).start();
//		}
		
	}
}

Java中對於多線程的實現,優先考慮的就是Runnable接口實現,並且永恆都是通過Thread類啓動多線程

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章