Javaスレッドの作成方法
Javaスレッドの作成方法は次のとおりです。
- Thread クラスを継承する:Thread クラスを継承するサブクラスを作成し、run() メソッドをオーバーライドしてスレッドが実行するタスクを定義します。その後、サブクラスのインスタンスを作成することでスレッドを作成して起動できます。
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();
- 匿名内部クラスの使用: スレッドオブジェクトを作成するときに、匿名内部クラスを使用して run() メソッドを実装できます。この方法は比較的シンプルで、それほど複雑ではないスレッドタスクを定義する場合に適しています。
Thread thread = new Thread() {
public void run() {
// 线程执行的任务
}
};
thread.start();
- Callable と Future を使う:Callable インターフェースを実装するクラスを作成し、その call() メソッドを実装することで、スレッドが実行するタスクを定義します。その後、ExecutorService の submit() メソッドを使用して Callable タスクをサブミットし、Future オブジェクトを返します。この Future オブジェクトを使用して、スレッドの実行結果を取得できます。
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 线程执行的任务,返回一个结果
return 1;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new MyCallable());
- スレッドプールの使用:ExecutorServiceを使ってスレッドプールを管理し、RunnableまたはCallableタスクを実行することでスレッドを作成できます。
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(new Runnable() {
public void run() {
// 线程执行的任务
}
});