共計 900 個字符,預(yù)計需要花費(fèi) 3 分鐘才能閱讀完成。
Java 實現(xiàn)多線程的方法有三種:
- 繼承 Thread 類:創(chuàng)建一個類繼承 Thread 類,并重寫 run() 方法。然后通過創(chuàng)建該類的實例調(diào)用 start() 方法啟動線程。
class MyThread extends Thread {public void run() {// 線程執(zhí)行的代碼}
public static void main(String[] args) {MyThread thread = new MyThread();
thread.start();}
}
- 實現(xiàn) Runnable 接口:創(chuàng)建一個類實現(xiàn) Runnable 接口,并實現(xiàn) run() 方法。然后通過創(chuàng)建該類的實例作為 Thread 類的構(gòu)造函數(shù)參數(shù),創(chuàng)建 Thread 對象并調(diào)用 start() 方法啟動線程。
class MyRunnable implements Runnable {public void run() {// 線程執(zhí)行的代碼}
public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();}
}
- 使用 Executor 框架:通過創(chuàng)建線程池,可以方便地管理和復(fù)用線程。可以使用 Executors 類中的靜態(tài)方法創(chuàng)建不同類型的線程池,并通過 submit() 方法提交 Runnable 對象或 Callable 對象。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyRunnable implements Runnable {public void run() {// 線程執(zhí)行的代碼}
public static void main(String[] args) {ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(new MyRunnable());
executor.shutdown();}
}
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完