Wednesday 2 March 2016

The Thread Class

As you might have guessed, threads are created and controlled as Thread objects. An instance of the java.lang.Thread class corresponds to a single thread. It contains methods to start, control, and interrupt the thread’s execution. Our plan here is to create a Thread object to handle our blinking code. We call the Thread’s start() method to begin execution. Once the thread starts, it continues to run until it completes its work, we interrupt it, or we stop the application. So, how do we tell the thread which method to run? Well, the Thread object is rather picky; it always expects to execute a method called run() to perform the action of the thread. The run() method can, however, with a little persuasion, be located in any class we desire. We specify the location of the run() method in one of two ways. First, the Thread class itself has a method called run(). One way to execute some Java code in a separate thread is to subclass Thread and override its run() method to do our bidding. Invoking the start() method of the subclass object causes its run() method to execute in a separate thread. It’s not usually desirable to create a subclass of Thread to contain our run() method. The Thread class has a constructor that takes an object as its argument. If we create a Thread object using this constructor and call its start() method, the Thread executes the run() method of the argument object rather than its own. In order to accomplish this, Java needs a guarantee that the object we are passing it does indeed contain a compatible run() method. We already know how to make such a guarantee: we use an interface. Java provides an interface named Runnable that must be implemented by any class that wants to become a Thread.

0 comments:

Post a Comment