It is often the case that a computer program needs to do more than one thing simultaneously. For example, a program might want to do some computation while waiting for user input. If the user presses a key, the program should perhaps stop the other task it is performing and respond.
A computer with a single CPU can run multiple programs simultaneously; for example, your computer might be playing audio in the background while you are actively inserting text into a Word document. Your operating system has a scheduler that determines which program, or process, gets to run at any given time.
Within a single process, threads are the programming abstraction that allow concurrent execution of several different tasks. Your programs all have a main thread that begins executing when your program starts. Your main thread may also spawn other threads that execute concurrently. Again, you can conceptually think of the threads executing at the same time, but really a scheduler is deciding which thread gets to run at any given time. As a result, you cannot guarantee how the individual statements in each thread are interleaved.
The following example creates a Spinner object that will cycle through the numbers 0-5 until the user hits enter. In order to count while listening for user input, the Spinner constructor creates a new thread that listens for user input.
This example also uses an anonymous inner class. The Runnable object created in the constructor is specified in an unnamed class.
The next example implements the same functionality as the previous, but the main thread listens for input while the other thread cycles through the numbers. This is a very common pattern for using threads.