Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA PROGRAMMING

Creating Thread

Creating  a Thread

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

  • You can implement the Runnable interface
  • You can extend the Thread class, itself

To implement Runnable, a class need only implement a single method called run(), which is declared like this:

public void run()

Inside run(), you will define the code that constitutes the new thread. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The on that we will use is shown here.

Thread(Runnable threadobj, String threadname)

In this constgructor, threadobj is an instance of a class that implements the Runnable interface. This defines where execution og the thread will begin. The name of the new thread is specified by threadname.

After the new thread is created, it will not start running until you call its start() method. The start() method is shown here:

void start()

Here is an example that creates a new thread and starts it running:






Previous

Next