Friday, 15 May 2015

Creating Threads in Java

 Threads aren't much use if you don't know how to create them. Fortunately, you have two options for creating and using threads in your own programs, which have already been alluded to when discussing the thread classes:
  • Derive your class from the Threadclass and override its runmethod.
  • Implement the Runnableinterface in your class and provide an implementation for the run method.
Both of these approaches revolve around providing a runmethod, which is where all the actual processing takes place. After a thread has been created and initialized, its runmethod is called and given the opportunity to perform whatever processing the thread is designed to provide. Because it provides all the processing power, the runmethod is the heart of a thread. It's not uncommon for the runmethod to consist of an infinite loop that performs some repetitive action like updating the frames of an animation. But enough about run for now; go ahead and create some threads!

Deriving from the ThreadClass

If your class isn't derived from a specific class, you can easily make it threaded by deriving it from the Threadclass. The following source code shows how to add thread functionality to a class by deriving from the Threadclass:
public class ThreadMe extends Thread {
  public run() {
    // do some busy work
  }
}
It's as easy as that! To use this class in a real program and set the thread in motion, you simply create a ThreadMeobject and call the startmethod inherited from Thread, like this:
ThreadMe me = new ThreadMe();
me.start();
The start method automatically calls run and gets the thread busy performing its processing. The thread will then run until the run method exits or the thread is stopped, suspended, or killed. If for some reason you want to stop the thread's execution, just call the stopmethod, like this:
me.stop();
If stopping the thread entirely is a little too abrupt, you can also temporarily pause it by calling the suspendmethod, like this:
me.suspend();
The suspend method puts the thread in a wait state, very similar to the state a thread enters when you call the wait method. When you decide the thread has waited long enough, just call resumeto get things rolling again, like this:
me.resume();

Implementing the RunnableInterface

If your class needs to derive from a class other than Thread, you are forced to implement the Runnableinterface to make it threaded. A very common situation where you have to do this is when an applet class needs to be threaded. Because applet classes must be derived from the Appletclass, and Java doesn't provide a mechanism for multiple inheritance, you have no other option but to implement the Runnableinterface to add threading support. You implement the Runnableinterface in a class like this:
public class ThreadYou implements Runnable {
   public run() {
     // do some busy work
   }
 }
As you can see, the only syntactic difference in this approach is that you use the implementskeyword instead of extends. However, notice that you can still use the extendskeyword to derive from another class, like this:
public class ThreadedApp extends Applet implements Runnable {
   public run() {
     // do some busy work
   }
 }
This is a very practical scenario involving an applet class with a run method that performs some type of threaded processing. Even though the definition of a class implementing the Runnableinterface is little different than directly deriving from Thread, there is a big difference when it comes to creating the thread and getting it running. Creating and running a threaded class implementing the Runnableinterface is a three-part process, as the following code shows:
ThreadYou you = new ThreadYou();
Thread t = new Thread(you);
t.start();
Unlike the previous approach involving creating a thread object and calling its start method, this approach requires you to create both an instance of your class and a separate instance of the Threadclass. You pass your object into the Threadclass's constructor, which gives it access to your runmethod. You then set the thread running by calling the thread object's start method. The thread in turn executes your object's runmethod. The thread knows your class has a runmethod because it implements the Runnableinterface.
If you have no need to access the thread after you get it started, the creation and starting of the thread can be combined into one statement, like this:
ThreadYou you = new ThreadYou();
new Thread(you).start();

This approach eliminates the creation of the local variable t, which makes the code a little more efficient. Of course, you may think the original code is easier to understand, in which case you should by all means stick with the clearer technique. 

No comments:

Post a Comment