Java Reference
In-Depth Information
A process with one thread
A process with two threads
Instruction-1
Instruction-2
Instruction-3
Instruction-4
Instruction-5
Instruction-6
Instruction-1
Instruction-4
Instruction-2
Instruction-5
Instruction-3
Instruction-6
Thread 1
Thread 2
Thread 1
Figure 6-3. Dividing the program logic to use two threads within a process
You can think of the relationship between a process and threads as
Process = address space + resources + threads
where threads are units of execution within the process; they maintain their own unique program counter and stack;
they share the process address space and resources; they are scheduled on a CPU independently and may execute on
different CPUs, if available.
Creating a Thread in Java
The Java API makes it easy to work with threads. It lets you represent a thread as an object. An object of the
java.lang.Thread class represents a thread. Creating and using a thread in Java is as simple as creating an object of
the Thread class and using that object in a program. Let's start with the simplest example of creating a thread in Java.
There are at least two steps involved in working with a thread:
Thread class
Creating an object of the
start() method of the Thread class to start the thread
Creating an object of the Thread class is the same as creating an object of any other classes in Java. In its simplest
form, you can use the default constructor of the Thread class to create a Thread object.
Invoking the
// Creates a thread object
Thread simplestThread = new Thread();
Creating an object of the Thread class allocates memory for that object on the heap. It does not start or run
the thread.
After you have created an object of the Thread class, you must call its start() method to start the thread
represented by that object.
// Starts the thread
simplestThread.start();
The start() method returns after doing some housekeeping work. It puts the thread in the runnable state. In this
state, the thread is ready to receive the CPU time. Note that invoking the start() method of a Thread object does not
guarantee “when” this thread will start getting the CPU time. That is, it does not guarantee when the thread will start
running. It just schedules the thread to receive the CPU time.
Let's write a simple Java program with the above two statements as shown in Listing 6-1. The program will not do
anything useful. However, it will get you started using threads.
 
 
Search WWH ::




Custom Search