このガイドでは、別のスレッドで Runnable.run()
メソッドのコードを実行する Runnable
クラスを実装する方法を示します。Runnable
を別のオブジェクトに渡し、それをスレッドにアタッチして実行することもできます。特定の操作を実行する 1 つ以上の Runnable
オブジェクトは、タスクと呼ばれることもあります。
Thread
と Runnable
は基礎的なクラスであり、それ自体では限られた機能しか持っていません。しかし、HandlerThread
、AsyncTask
、IntentService
などの強力な Android クラスの基礎となっています。さらに、ThreadPoolExecutor
クラスも Thread
と Runnable
を基礎としており、スレッドとタスクキューを自動的に管理し、複数のスレッドを並行して実行することもできます。
Runnable を実装するクラスを定義する
Runnable
を実装するクラスの作成は簡単です。次に例を示します。
Kotlin
class PhotoDecodeRunnable : Runnable { ... override fun run() { /* * Code you want to run on the thread goes here */ ... } ... }
Java
public class PhotoDecodeRunnable implements Runnable { ... @Override public void run() { /* * Code you want to run on the thread goes here */ ... } ... }
run() メソッドを実装する
クラスでは、Runnable.run()
メソッドに実行されるコードが含まれています。通常、Runnable
では何でも使用できます。ただし、Runnable
は UI スレッドでは実行されないため、View
オブジェクトなどの UI オブジェクトを直接変更できないことに注意してください。UI スレッドと通信するには、UI スレッドと通信するのレッスンで説明されている手法を使用する必要があります。
run()
メソッドの開始時に、THREAD_PRIORITY_BACKGROUND
を使用して Process.setThreadPriority()
を呼び出すことによって、バックグラウンドの優先順位を使用するようにスレッドを設定します。このアプローチにより、Runnable
オブジェクトのスレッドと UI スレッド間のリソースの競合が軽減されます。
Thread.currentThread()
を呼び出して、Runnable
オブジェクトの Thread
への参照を Runnable
自体に保存する必要もあります。
次のスニペットは、run()
メソッドを設定する方法を示しています。
Kotlin
class PhotoDecodeRunnable : Runnable { ... /* * Defines the code to run for this task. */ override fun run() { // Moves the current Thread into the background android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND) ... /* * Stores the current Thread in the PhotoTask instance, * so that the instance * can interrupt the Thread. */ photoTask.setImageDecodeThread(Thread.currentThread()) ... } ... }
Java
class PhotoDecodeRunnable implements Runnable { ... /* * Defines the code to run for this task. */ @Override public void run() { // Moves the current Thread into the background android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); ... /* * Stores the current Thread in the PhotoTask instance, * so that the instance * can interrupt the Thread. */ photoTask.setImageDecodeThread(Thread.currentThread()); ... } ... }
詳細
Android でのマルチスレッド操作の詳細については、プロセスとスレッドの概要ガイドをご覧ください。
サンプルアプリ
このガイドのコンセプトを試すには、ThreadSample
をダウンロードします。