在Java之中,實現多線程有兩種途徑:
繼承Thread類
實現Runnable接口(Callable接口)
1.繼承Thread類
Thread類是一個支持多線程的功能類
格式: class 名稱 extends Thread {} //多線程操作類
注意,在多線程的每個主體類之中,都要覆寫Thread類中的run()方法
格式:public void fun() {} //沒有返回值,線程一旦開始,就要一直執行,不能夠返回內容
例:
class MyThread extends Thread {
private String name;
public MyThread (String name) {
this.name = name ;
}
public void run() {
for(int x=0 ; x < 200 ; x++ ) {
System.out.println(this.name + "--->" + x);
}
}
}
public class Nice {
public static void main(String args[]) {
MyThread mt1 = new MyThread("A") ;
MyThread mt2 = new MyThread("B") ;
//mt1.run(); 其實這並不是多線程的執行,輸出中沒有實現多線程的特點
//mt2.run();
mt1.start(); //搶佔資源,多線程的執行
mt2.start();
}
}
爲什麼啓動多線程不用run(),用start()呢,因爲start()方法不僅僅要啓動多線程執行代碼,還要根據不同的操作系統進行資源的分配
附:Thread常用方法
類別 | 方法簽名 | 簡介 |
---|---|---|
線程的創建 | Thread() | |
線程的創建 | Thread(String name) | |
線程的創建 | Thread(Runnable target) | |
線程的創建 | Thread(Runnable target,String name) | |
線程的方法 | void start() | 啓動線程 |
線程的方法 | static void sleep(long millis) | 線程休眠 |
線程的方法 | static void sleep(long millis,int nanos) | 線程休眠 |
線程的方法 | void join() | 使其他線程等待當前線程終止 |
線程的方法 | void join(long millis) | 使其他線程等待當前線程終止 |
線程的方法 | void join(long millis,int nanos) | 使其他線程等待當前線程終止 |
線程的方法 | static void yield() | 當前運行線程釋放處理器資源 |
獲取線程引用 | static Thread currentThread() | 返回當前運行的線程引用 |
2.實現Runnable接口
雖然Thread很好,但是它本身有一個缺陷,那就是他的繼承問題,而接口不一樣,Runnable接口就是爲了解決單繼承的限制
格式:
@FunctionalInterface
public interface Runnable {
public void run();
}
例:
class MyThread implements Runnable {
private String name;
public MyThread (String name) {
this.name = name ;
}
public void run() {
for(int x=0 ; x < 200 ; x++ ) {
System.out.println(this.name + "--->" + x);
}
}
}
public class Nice {
public static void main(String args[]) {
MyThread mt1 = new MyThread("A") ;
MyThread mt2 = new MyThread("B") ;
//mt1.start();
//mt2.start();
}
}
//與繼承Thread類相比,其實結構上沒有什麼區別,但是有一個地方不同
//繼承Thread類,可以直接繼承start方法
//但是,實現Runnable接口,就沒有start方法啦
引出:不管什麼情況下,如果啓動多線程一定要依靠Thread類完成!
構造方法:public Thread(Runnable target),接收的是Runnable接口對象
class MyThread implements Runnable {
private String name;
public MyThread (String name) {
this.name = name ;
}
public void run() {
for(int x=0 ; x < 200 ; x++ ) {
System.out.println(this.name + "--->" + x);
}
}
}
public class Nice {
public static void main(String args[]) {
MyThread mt1 = new MyThread("A") ;
MyThread mt2 = new MyThread("B") ;
new Thread(mt1).start(); //實例化,使用了Thread類,爲的是調用start()方法
new Thread(mt2).start();
}
}
//此時避免了單繼承侷限,實際應用中,Runnable接口是比較實用的