Software Design and Development :: CS 246

06 Prepare : Reading

Multithreading

Objectives

Multithreading

Most of the programs you've written up to this point have been doing exactly one thing at a time. They start in some kind of main() function, executing that code one line at a time until the function ends, thus ending the program.

Sometimes, we need our programs to be able to do more than one thing at a time. This is especially common in programs with GUIs, such as an Android app. For example, imagine if every time you opened a new tab in your web browser and loaded a page, the entire browser froze while waiting for the page to finish loading.

To prevent this, the page loading happens on another thread. You can think of a thread as a lightweight subprocess. Or, another process running within your progam at the same time as the main thread.

In the case of real browsers, and most other GUI applications, the main thread is the one responsible for listening for and responding to mouse clicks and keyboard input, while other threads are used to execute tasks that might take a long time to complete, such as loading a web page, executing a database query, or performing a complex calculation.

There are two main ways to use threading in a pure-Java application. The first is to subclass the Thread class. This is less desirable because it forces you into a specific inheritance hierarchy.

The more common way is to have your class implement the Runnable interface, which defines a single requirement: a public method called run(), which takes no parameters and returns void.

Multithreading in Android

There are several ways to handle multithreading in Android, many of which also take advantage of the Runnable interface.

Preparation Assignment

Before Class, complete the following:

  1. Read this tutorial showing how Runnable works.

  2. Read this introduction to Processes and Threads on Android.

  3. You may see references to AsyncTask in online examples for Android development. In 2019, AsyncTask was deprecated due to concerns of misuse and memory leaks.

Reading Quiz

Don't forget to take the Reading Quiz in I-Learn. This quiz can be taken as many times as you like, but you must score at least 90% to pass. If you fail the quiz, review the relevant parts of the reading and try again.

As before, one of the quiz questions is a "deep thought" question whose answer won't come directly from the reading.