Java Reference
In-Depth Information
Chapter 6
Threads
In this chapter, you will learn
What threads are
How to create threads in Java
How to execute your code in separate threads
What the Java Memory Model is
The life cycle of threads
How to use object monitors to synchronize access to a critical section by threads
How to interrupt, stop, suspend, and resume threads
Atomic variables, explicit locks, synchronizer, executor framework, fork/join framework, and
thread-local variables
What Is a Thread?
Threads are a vast topic. They deserve an entire book. This chapter does not discuss the concept of threads in detail.
Rather, it discusses how to work with threads using Java constructs. Before I define the term thread , it is necessary to
understand the meaning of some related terms, such as program, process, multitasking, sequential programming,
concurrent programming, etc.
A program is an algorithm expressed in a programming language. A process is a running instance of a program
with all system resources allocated by the operating system to that instance of the program. Typically, a process
consists of a unique identifier, a program counter, executable code, an address space, open handles to system
resources, a security context, and many other things. A program counter , also called an instruction pointer, is a value
maintained in the CPU register that keeps track of the instruction being executed by the CPU. It is automatically
incremented at the end of the execution of an instruction. You can also think of a process as a unit of activity (or a unit
of work, or a unit of execution, or a path of execution) within an operating system. The concept of process allows one
computer system to support multiple units of executions.
Multitasking is the ability of an operating system to execute multiple tasks (or processes) at once. On a single
CPU machine, multitasking is not possible in a true sense because one CPU can execute instructions for only one
process at a time. In such a case, the operating system achieves multitasking by dividing the single CPU time among
all running processes and switching between processes quickly enough to give an impression that all processes are
running simultaneously. The switching of the CPU among processes is called a context switch . In a context switch,
the running process is stopped, its state is saved, the state of the process that is going to get the CPU is restored, and
the new process is run. It is necessary to save the state of the running process before the CPU is allocated to another
 
Search WWH ::




Custom Search