Javaでマルチスレッドを実装する方法は何種類ありますか?

Javaで複数スレッドを実装する方法はいくつかあります:

  1. Threadクラスを継承する:Threadクラスを継承したクラスを作成し、run()メソッドをオーバーライドして、スレッドが実行するタスクをrun()メソッドで定義します。その後、そのクラスのオブジェクトを作成し、start()メソッドを呼び出してスレッドを開始します。
class MyThread extends Thread {
    public void run() {
        // 线程要执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. Runnableインターフェースを実装する:クラスを作成し、Runnableインターフェースを実装し、run()メソッドをオーバーライドし、run()メソッドの中でスレッドが実行するタスクを定義します。次に、そのクラスのオブジェクトを作成し、Threadクラスのコンストラクタにパラメータとして渡し、最後にstart()メソッドを呼び出してスレッドを開始します。
class MyRunnable implements Runnable {
    public void run() {
        // 线程要执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
  1. CallableとFutureインターフェースの使用:Callableインターフェースを実装し、call()メソッドをオーバーライドするクラスを作成し、call()メソッド内でスレッドが実行するタスクを定義します。次に、そのクラスのオブジェクトを作成し、ExecutorServiceのsubmit()メソッドの引数として渡します。Futureオブジェクトを使用してスレッドの実行結果を取得できます。
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() {
        // 线程要执行的任务
        return "任务执行结果";
    }
}

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フレームワークが提供するスレッドプールを使用する:スレッドの生成と実行を管理するためにExecutorフレームワークが提供するスレッドプールを使用します。Executorsクラスの静的メソッドを使用して、さまざまなタイプのスレッドプールを作成できます。
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() {
                    // 线程要执行的任务
                }
            });
        }
        executorService.shutdown();
    }
}
bannerAds