共計 786 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以通過以下方式創建多線程:
- 繼承 Thread 類:創建一個新的類并繼承 Thread 類,重寫 run() 方法來定義線程執行的任務。然后創建該類的對象并調用 start() 方法啟動線程。
public class MyThread extends Thread {public void run() {// 線程執行的任務
}
}
public class Main {public static void main(String[] args) {MyThread thread = new MyThread();
thread.start();}
}
- 實現 Runnable 接口:創建一個實現了 Runnable 接口的類,實現 run() 方法來定義線程執行的任務。然后創建該類的對象,并將其作為參數傳遞給 Thread 類的構造方法,最后調用 start() 方法啟動線程。
public class MyRunnable implements Runnable {public void run() {// 線程執行的任務
}
}
public class Main {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();}
}
- 使用匿名內部類:可以直接在創建 Thread 對象時使用匿名內部類來實現線程執行的任務。
public class Main {public static void main(String[] args) {Thread thread = new Thread(() -> {// 線程執行的任務
});
thread.start();}
}
無論采用哪種方式,創建多線程后,可以通過調用 start() 方法啟動線程,并在 run() 方法中定義線程執行的任務。
丸趣 TV 網 – 提供最優質的資源集合!
正文完