java實(shí)現(xiàn)多線程的方式有哪幾種

小億
86
2024-01-23 10:15:27

Java實(shí)現(xiàn)多線程的方式有以下幾種:

  1. 繼承Thread類:創(chuàng)建一個(gè)類,繼承自Thread類,并重寫run()方法,在run()方法中定義線程要執(zhí)行的任務(wù)。然后創(chuàng)建該類的對(duì)象,并調(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();
    }
}
  1. 實(shí)現(xiàn)Runnable接口:創(chuàng)建一個(gè)類,實(shí)現(xiàn)Runnable接口,并重寫run()方法,在run()方法中定義線程要執(zhí)行的任務(wù)。然后創(chuàng)建該類的對(duì)象,并將其作為參數(shù)傳遞給Thread類的構(gòu)造函數(shù),最后調(diào)用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();
    }
}
  1. 使用Callable和Future接口:創(chuàng)建一個(gè)類,實(shí)現(xiàn)Callable接口,并重寫call()方法,在call()方法中定義線程要執(zhí)行的任務(wù)。然后創(chuàng)建該類的對(duì)象,并將其作為參數(shù)傳遞給ExecutorService的submit()方法,通過Future對(duì)象可以獲取線程的執(zhí)行結(jié)果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable<String> {
    public String call() {
        // 線程要執(zhí)行的任務(wù)
        return "任務(wù)執(zhí)行結(jié)果";
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(callable);
        String result = future.get();
        System.out.println(result);
        executorService.shutdown();
    }
}
  1. 使用線程池:通過Executor框架提供的線程池來管理線程的創(chuàng)建和執(zhí)行??梢允褂肊xecutors類提供的靜態(tài)方法創(chuàng)建不同類型的線程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new Runnable() {
                public void run() {
                    // 線程要執(zhí)行的任務(wù)
                }
            });
        }
        executorService.shutdown();
    }
}

0