This chapter is from the book

Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.

4.2

Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.

4.3

Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

4.4

Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.

Supplementary Objectives

Recognize conditions that might prevent a thread from executing.

Write code to start and stop a thread.

Understand aspects of thread behavior that are not guaranteed.

13.1 Multitasking

Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:

Process-based multitasking

Thread-based multitasking

At the coarse-grain level there is process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor. At the fine-grain level there is thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word-processor that is printing and formatting text at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program concurrently. The sequence of code executed for each task defines a separate path of execution, and is called a thread (of execution).

In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted, for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.

Some advantages of thread-based multitasking as compared to process-based multitasking are:

threads share the same address space

context switching between threads is usually less expensive than between processes

the cost of communication between threads is relatively low

Java supports thread-based multitasking and provides high-level facilities for multithreaded programming. Thread safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.