Creating a Thread in Advanced Java Programming

Home  »  Java  »  Advance Java »  »  MultiThreading »  Creating Thread

In the most general sense, a thread is created by instantianting an object of the type Thread. Java defines two ways in which this can be accomplished.

  1. Implement the Runnable interface.
  2. Extend the Thread class, itself.

The Thread class is part of the java.lang package.

The following two sections look at each technique, in turn.

Implementing Runnable

The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. To implement Runnable, a class need only implements a single method called run(), which is declared as follows:



Inside run(), the code that constitutes the new thread is defined. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run() establishes the entry point for another, concurrent thread of execution within a program. This thread will end when the run() signature execution completes.

After creating a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one used is as shown:



In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begain. The name of the new thread is specified by the string value threadName.

After the new thread is created, it wil not start running until its start() method is called, which is declared within Thread. In essence, start() executes a call to run(). The start() method is shown below:



The following example creates a new thread and starts it running:



The above code will be stored in the file called ThreadDemo.java, which on compilation will crate a class file called ThreadDemo.class. Now compile this file using below commands in the DOS mode:

C:\>jdk1.4\bin>javac ThreadDemo.java
C:\>jdk1.4\bin>java ThreadDemo


"Output of ThreadDemo.class"


Download Complete Program

  -  



MultiThreading


Thread Life Cycle Main Thread
Creating A Thread Thread Priority
Extending The Thread Class Writing Applets With Threads




No comments:

Post a Comment