Javaのマルチスレッド並行処理を実現するには

Java ではコンカレント実行をマルチスレッドで実装する方法はいくつかあります。以下はよく使われる方法の一部です。

  1. スレッドクラスを継承する: スレッドクラスを継承したサブクラスを作成し、run()メソッドをオーバーライドする。サブクラスのインスタンスを複数作成し、start()メソッドを呼び出してスレッドを起動する。
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
  1. Runnableインターフェースを実装:Runnableインターフェースを実装したクラスを作成し、メソッドrun()を実装します。次に、そのクラスのインスタンスを複数作成し、それらをThreadクラスのコンストラクタへ引数として渡し、メソッドstart()を呼び出してスレッドを開始します。
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable();
MyRunnable runnable2 = new MyRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}
  1. スレッドプールを使う: スレッドプールを作成し、ExecutorServiceインターフェースのsubmit()メソッドまたはexecute()メソッドを呼び出してタスクを提出します。スレッドプールはスレッドの作成と破棄を自動的に管理します。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyTask implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new MyTask());
executor.submit(new MyTask());
executor.shutdown();
}
}

マルチスレッドによる並列処理を行う際は、どの方法を用いる場合であっても、スレッドセーフティやデータの同期について注意を払う必要があります。共有データへの並列アクセスによる不具合を防ぐために、synchronized キーワード、または Lock オブジェクトによるスレッド間の同期を実現することができます。

bannerAds