Java Reference
In-Depth Information
These objectives are found in Section 4 of the SCJP exam
objectives. The exam tests your knowledge of writing and
using threads in Java, including thread states, synchronization,
and the wait and notify methods of Object . This chapter covers these topics in detail.
Overview of Threads
Before we discuss the details and semantics of concurrency and threads, I want to discuss
some terminology. Concurrency refers to doing multiple tasks at the same time. Your
computer's operating system runs programs concurrently, and a program that runs
on a computer is referred to as a process. A process consists of allocated memory and
resources, including the executable code of your program.
Concurrency in processes is handled at the operating system level, and a typical Java
program is not interested in multiple processes. Instead, Java programs often need to
perform simultaneous tasks within a single process by using multiple threads to implement
concurrency. A thread is a path of execution, a block of code that executes within a process
and has access to the process memory. Each thread within a process executes concurrently,
and the JVM schedules the threads with the CPU. The number of threads running at any
given time depends on the number of CPUs on the machine. For example, if your machine
has one CPU, only one thread can be executing at a time. What are the other threads doing
when the CPUs are busy? Depending on their state, they are either waiting for the JVM to
schedule them with the next available CPU or waiting for a particular event to occur.
Every stand-alone Java program has system threads that run in the background of the
application. For example, garbage collection is a task that always needs to be running and
is implemented in a system thread. From a programmer's point of view, you are typically
more concerned with user-defi ned threads , the threads that you write to perform a specifi c
task. A stand-alone Java application starts with a single thread associated with the main
method. This main thread can start new user-defi ned threads, allowing you to break down
your program into simultaneous, logical units of work.
This chapter discusses in detail the steps involved in writing and starting new user-
defi ned threads. We will also discuss the various states that a thread can be in, along with
thread synchronization and the wait and notify methods of Object . Let's start with a
discussion on how to write and start a thread.
Search WWH ::




Custom Search