Background: Processes

To understand threads, we start with processes. Processes are the operating system's notion of 'program'. A process is best characterized by considering it's 'state', that is, all of the information required to store, restart, and continue executing the process. [Note: This notion of the state of a computation is a very general and important one. The notion of process it the operating system's view of a generic computation. It is occasionally useful for the programmer to keep the state of some algorithm or computation explicitly so it can be stopped and started within the program. Computations built with this property are often called 're-entrant' and are important in system programming and distributed or asynchronour programming.] The state of a process includes:

Threads: Motivation

Most programs we have seen so far had a single thread of control. In these programs, execution starts at main and follows sequentially, branching via control structures and method calls. Even in event-based programs, where control follows the event loop, extracting events and calling handlers, there is still a single control thread. This is clear when an event handler loops forever, the program locks up.

However, it is often convenient to have multiple threads of control; to have the program doing more than one thing at once. For example:

There are several ways to accomplish this:
Use a variation on event-based programming in which control loops over all of the task is the systems, running each until it blocks or surrenders control. For I/O based programs where we are waiting for multiple channels, we can sleep on a timer and periodically check all sourcesfor something to do. This is called "polling". These approaches in essences require building a mini operating system into the program. The scheme has some disadvantages: the tasks must remember to surrender control or other tasks are starved, and the handler routines for each task cannot use the call stack and local variables to store task state.

Since this is a common programming circumstance, most programming systems now provide a capability to address these issues, usually called threads.


Threads in Java

Thread Scheduling in Java

Thread Synchronization

Java Synchronization

Java does not support mutexes or semaphores. Instead it has a mechanism that integrates nicely with OO programming.


Attempts to make program execution deterministic can lead to other problems if done naively.

Final Thread Notes;

Common Thread Patterns