共計 476 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中創建子線程可以有兩種方式:
- 繼承 Thread 類并重寫 run() 方法:
public class MyThread extends Thread {@Override
public void run() {// 子線程的具體邏輯
}
}
public static void main(String[] args) {MyThread myThread = new MyThread();
myThread.start(); // 啟動子線程
}
- 實現 Runnable 接口并實現 run() 方法:
public class MyRunnable implements Runnable {@Override
public void run() {// 子線程的具體邏輯
}
}
public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 啟動子線程
}
無論使用哪種方式,都需要調用 start() 方法來啟動子線程。
丸趣 TV 網 – 提供最優質的資源集合!
正文完