在Java中,實現(xiàn)多線程主要有兩種方法:繼承Thread類或實現(xiàn)Runnable接口。以下是兩種方法的簡單介紹和示例:
方法一:繼承Thread類
示例代碼:
class MyThread extends Thread {
public void run(){
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 啟動線程
}
}
方法二:實現(xiàn)Runnable接口
示例代碼:
class MyRunnable implements Runnable {
public void run(){
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r); // 將Runnable對象作為參數(shù)傳遞給Thread構造函數(shù)
t.start(); // 啟動線程
}
}
需要注意的是,實現(xiàn)Runnable接口的方式比繼承Thread類更為靈活,因為Java不支持多重繼承,但允許實現(xiàn)多個接口。因此,如果一個類已經(jīng)繼承了其他類,但仍然需要實現(xiàn)多線程,那么實現(xiàn)Runnable接口是一個更好的選擇。