共計(jì) 722 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Java 中,有兩種常見的方法來創(chuàng)建多線程:
- 繼承 Thread 類:創(chuàng)建一個(gè)繼承自 Thread 類的子類,重寫 run() 方法,并在 run() 方法中定義線程要執(zhí)行的任務(wù)。然后創(chuàng)建子類的實(shí)例,調(diào)用 start() 方法來啟動(dòng)線程。例如:
class MyThread extends Thread {public void run() {// 線程要執(zhí)行的任務(wù)}
}
public class Main {public static void main(String[] args) {MyThread thread = new MyThread();
thread.start(); // 啟動(dòng)線程}
}
- 實(shí)現(xiàn) Runnable 接口:創(chuàng)建一個(gè)實(shí)現(xiàn) Runnable 接口的類,實(shí)現(xiàn) run() 方法,并在 run() 方法中定義線程要執(zhí)行的任務(wù)。然后創(chuàng)建該類的實(shí)例,并將實(shí)例作為參數(shù)傳遞給 Thread 類的構(gòu)造方法。最后調(diào)用 Thread 類的 start() 方法來啟動(dòng)線程。例如:
class MyRunnable implements Runnable {public void run() {// 線程要執(zhí)行的任務(wù)}
}
public class Main {public static void main(String[] args) {MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 啟動(dòng)線程}
}
這兩種方法都可以實(shí)現(xiàn)多線程,但通常推薦使用實(shí)現(xiàn) Runnable 接口的方式,因?yàn)?Java 只支持單繼承,通過實(shí)現(xiàn)接口的方式可以避免類繼承的限制。此外,實(shí)現(xiàn) Runnable 接口的方式還可以更好地實(shí)現(xiàn)代碼的解耦和復(fù)用。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完