マルチスレッド / コールバック入門
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Kotlin を使った Android アプリの開発コースでは、マルチスレッドの概念と用語を理解していることを前提としています。このページは、以前の学習内容を簡単に説明し、参照するためのものです。
モバイル デバイスにはプロセッサがあり、最近は、ほとんどのデバイスが複数のハードウェア プロセッサを備え、それぞれが同時にプロセスを実行するようになっています。これをマルチプロセスといいます。
プロセッサをより効率的に使用するために、オペレーティング システムは、アプリに 1 つのプロセス内で複数の実行スレッドを作成させることができます。これをマルチスレッドといいます。

これは、複数の章を同時に読んだり、ある章を読んだ後に別の書籍に切り替えたりしながら書籍をすべて読み終わることができても、同時に複数の書籍を読むことはできないと考えることができます。
このようにスレッドをすべて管理するには、インフラストラクチャがいくつか必要です。

スケジューラは、優先度などの問題を考慮し、すべてのスレッドを実行して完了することができるようにします。書籍が棚にいつまでも置かれてほこりを集めることはありません。ただし、書籍の内容が非常に長い場合、または後で読むことができる場合には、時間が経ってから送られてくることもあり得ます。
ディスパッチャはスレッドを設定します。つまり、読む必要がある書籍を送信して、処理を行うコンテキストを指定します。コンテキストは、独立した専用の読書ルームと考えることができます。ユーザー インターフェース操作に最適なコンテキストもあれば、入出力操作の処理に特化したコンテキストもあります。
もう 1 つの注意点は、ユーザー向けのアプリには通常、フォアグラウンドで実行されるメインスレッドがあり、メインスレッドは、バックグラウンドで実行される他のスレッドをディスパッチできることです。
Android では、メインスレッドは UI の更新をすべて処理する単一のスレッドです。このメインスレッド(UI スレッドとも呼ばれます)は、すべてのクリック ハンドラとその他の UI とライフサイクル コールバックを呼び出すスレッドでもあります。UI スレッドがデフォルトのスレッドです。アプリが明示的にスレッドを切り替えたり、別のスレッドで実行されるクラスを使用したりしない限り、アプリのすべての操作はメインスレッドで実行されます。
これにより、潜在的な課題が発生します。スムーズなユーザー エクスペリエンスを確保するには、UI スレッドをスムーズに実行する必要があります。ユーザーが視認できるような途切れがなくアプリを表示させるには、メインスレッドは 16 ミリ秒以上ごとに、または 1 秒あたり約 60 フレームで画面を更新する必要があります。この速度では、人間はフレームの変化を滑らかに感じます。この効果を実現するには、多数のフレームを短時間で処理する必要があります。
したがって、Android では UI スレッドのブロックを回避することが重要です。この場合、ブロックとは、データベースの更新などが完了するまで待機している間に、UI スレッドが何も実行していないことを意味します。

インターネットからのデータの取得、サイズの大きいファイルの読み取り、データベースへのデータの書き込みなど、多くの一般的なタスクには 16 ミリ秒を超える時間がかかります。したがって、メインスレッドからこのようなタスクを実行するためにコードを呼び出すと、アプリの一時停止、途切れ、またはフリーズが発生する可能性があります。メインスレッドを長時間ブロックすると、アプリがクラッシュして、「アプリケーション応答なし」(ANR)のダイアログが表示される場合もあります。
コールバック
メインスレッドの外部から作業を完了するには、いくつかの方法があります。
メインスレッドをブロックせずに長時間実行タスクを実行するためのパターンの 1 つがコールバックです。コールバックを使用すると、長時間実行されるタスクをバックグラウンド スレッドで開始できます。タスクが完了すると、コールバック(引数として提供される)が呼び出され、メインスレッドで結果のコードを通知します。
コールバックは優れたパターンですが、デメリットもあります。コールバックを多用するコードは読み取りと推測が困難になる可能性があります。このコードは順次読み取れるようになっていますが、コールバック コードは将来的には非同期で実行されるようになります。また、コールバックでは、一部の言語機能(例外など)を使用できません。
コルーチン
Kotlin では、コルーチンは、長時間実行タスクをスムーズかつ効率的に処理するためのソリューションです。Kotlin コルーチンを使用すると、コールバック ベースのコードを順次コードに変換できます。通常、コードを順番に記述すると読みやすくなり、例外などの言語機能を使用できるようになります。最終的に、コルーチンとコールバックでも同様に同じタスクが実行されます。長時間実行タスクが結果を取得するのを待ってから、タスクの実行を続行します。
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-08-19 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-08-19 UTC。"],[],[],null,["# Multi-threading & callbacks primer\n\nThe\n[Developing Android Apps in Kotlin course](https://codelabs.developers.google.com/codelabs/kotlin-android-training-welcome/index.html?index=..%2F..index#0)\nassumes that you are familiar with the concept and terminology of\nmulti-threading. This page is a high-level introduction and refresher.\n\nMobile devices have processors, and these days, most devices have multiple\nhardware processors that each run processes concurrently. This is called\n*multiprocessing*.\n\nTo use processors more efficiently, the operating system can enable an\napplication to create more than one thread of execution within a process. This\nis called *multi-threading*.\n\nYou can think of it as reading multiple books at the same time, switching\nbetween books after each chapter, eventually finishing all books, but you can't\nread more than one book at the exact same time.\n\nIt takes a bit of infrastructure to manage all those threads.\n\nThe *scheduler* takes into account things such as priorities, and makes sure all\nthe threads get to run and finish. No book is allowed to sit in the shelf\nforever and gather dust, but if a book is very long, or can wait, it may take a\nwhile before it gets sent your way.\n\nThe *Dispatcher* sets up threads, that is, it sends you books that you need to\nread, and specifies a **context** for that to happen in. You can think of the\ncontext as a separate, specialized reading room. Some contexts are best for user\ninterface operations, and some are specialized to deal with input/output\noperations.\n\nThe only other thing to know is that a user-facing application usually has a\n*main thread* that runs in the foreground and can dispatch other threads that\nmay run in the background.\n\nOn Android, the main thread is a single thread that handles all updates to the\nUI. This main thread, also called the *UI thread*, is also the thread that calls\nall click handlers and other UI and lifecycle callbacks. The UI thread is the\ndefault thread. Unless your app explicitly switch threads or uses a class that\nruns on a different thread, everything your app does is on the main thread.\n\nThis creates a potential challenge. The UI thread has to run smoothly to\nguarantee a great user experience. For your app to display to the user without\nany visible pauses, the main thread has to update the screen every 16 ms or more\noften, or at about 60 frames per second. At this speed, humans perceive the\nchange of frames as completely smooth. That's a lot of frames and little time.\nTherefore, on Android it's essential to avoid blocking the UI thread. *Blocking*\nin this context means the UI thread is not doing anything at all while it waits\nfor something like a database to finish updating.\n\nMany common tasks take longer than 16 milliseconds, such as fetching data from\nthe internet, reading a large file, or writing data to a database. Therefore,\ncalling code to perform tasks like those from the main thread can cause the app\nto pause, stutter, or even freeze. And if you block the main thread for too\nlong, the app may even crash and present an \"application not responding\" (ANR)\ndialog.\n\nCallbacks\n---------\n\nYou have several options for how to get work done off of from the main thread.\n\nOne pattern for performing long-running tasks without blocking the main thread\nis *[callbacks](https://en.wikipedia.org/wiki/Callback_(computer_programming))*.\nBy using callbacks, you can start long-running tasks on a background thread.\nWhen the task completes, the callback, supplied as an argument, is called to\ninform your code of the result on the main thread.\n\nCallbacks are a great pattern, but they have a few drawbacks. Code that heavily\nuses callbacks can become hard to read and harder to reason about. Because while\nthe code looks sequential, the callback code will run at some asynchronous time\nin the future. In addition, callbacks don't allow the use of some language\nfeatures, such as exceptions.\n\nCoroutines\n----------\n\nIn Kotlin,\n*[coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)*\nare the solution for handling long-running tasks elegantly and efficiently.\nKotlin coroutines let you convert callback-based code to sequential code. Code\nwritten sequentially is typically easier to read, and can even use language\nfeatures such as exceptions. In the end, coroutines and callbacks do exactly the\nsame thing: wait until a result is available from a long-running task and\ncontinue execution."]]