Java Reference
In-Depth Information
Listing 6-1. The Simplest Thread in Java
// SimplestThread.java
package com.jdojo.threads;
public class SimplestThread {
public static void main(String[] args) {
// Creates a thread object
Thread simplestThread = new Thread();
// Starts the thread
simplestThread.start();
}
}
When you run the SimplestThread class, you do not see any output. The program will start and finish silently.
Even though you did not see any output, here are few things the JVM did when the two statements in the main()
method were executed:
simplestThread.start() , is executed, the JVM scheduled this
When the second statement,
thread for execution.
At some point in time, this thread got the CPU time and started executing. What code does a
thread in Java start executing when it gets the CPU time?
run() method. You can define the run()
method to be executed by a thread when you create an object of the Thread class. In your
case, you created an object of the Thread class using its default constructor. When you use
the default constructor of the Thread class to create its object (as in new Thread() ), the run()
method of the Thread class is called when the thread starts its execution. The following
sections in this chapter will explain how to define your own run() method for a thread.
A thread in Java always starts its execution in a
run() method of the Thread class checks how the object of the Thread class was created.
If the thread object was created using the default constructor of the Thread class, it does not do
anything, and immediately returns. Therefore, in your program, when the thread got the CPU
time, it called the run() method of the Thread class, which did not execute any meaningful
code, and returned.
The
run() method, the thread is dead, which means the
thread will not get the CPU time again.
When the CPU finishes executing the
Figure 6-4 depicts how the simplest thread example works.
Search WWH ::




Custom Search