Javaのマルチスレッド化の実装方法にはどのようなものがありますか?
Javaでマルチスレッドを実現するには、以下の方法があります。
- スレッドの継承: Thread クラスを継承したサブクラスを作成し、run() メソッドを実装します。start() メソッドを呼び出すことで新しいスレッドを開始します。
class MyThread extends Thread {
public void run() {
// 线程要执行的代码
}
}
MyThread thread = new MyThread();
thread.start();
- Runnableインタフェースを実装:Runnableインタフェースを実装したクラスを作成し、その中のrun()メソッドを実装します。Runnableオブジェクトをスレッドのコンストラクタに渡すことでスレッドオブジェクトを作成し、続いてスレッドのstart()メソッドを呼び出して新しいスレッドを開始します。
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的代码
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
- Callableインターフェイスを実装する: Callableインターフェイスを実装したクラスを作成し、call()メソッドを実装する。ExecutorServiceオブジェクトを作成し、そのsubmit()メソッドを使用してCallableオブジェクトを送信し、Futureオブジェクトを取得する。Futureオブジェクトのget()メソッドを使用して、スレッド実行結果を取得できます。
class MyCallable implements Callable<Integer> {
public Integer call() {
// 线程要执行的代码
return result;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
MyCallable callable = new MyCallable();
Future<Integer> future = executor.submit(callable);
Integer result = future.get();
- 匿名クラスまたはラムダ式を使用する:Runnable インターフェースを実装するために匿名クラスまたはラムダ式を使用できます。
Runnable runnable = new Runnable() {
public void run() {
// 线程要执行的代码
}
};
Thread thread = new Thread(runnable);
thread.start();
あるいは
Runnable runnable = () -> {
// 线程要执行的代码
};
Thread thread = new Thread(runnable);
thread.start();
上記はマルチスレッドを実現する一般的な手法で、それぞれ適した場面があり、具体的なニーズに合った手法を選択してマルチスレッドを実現します。