Which of the following methods will start the thread public class Mythread?

Conceptually, a thread is a flow of control within a program. A thread is similar to the more familiar notion of a process, except that multiple threads within the same application share much of the same state—in particular, they run in the same address space. It’s not unlike a golf course, which many golfers use at the same time. Sharing the same address space means that threads share instance variables but not local variables, just like players share the golf course but not personal things like clubs and balls.

Multiple threads in an application have the same problems as the golfers—in a word, synchronization. Just as you can’t have two sets of players blindly playing the same green at the same time, you can’t have several threads trying to access the same variables without some kind of coordination. Someone is bound to get hurt. A thread can reserve the right to use an object until it’s finished with its task, just as a golf party gets exclusive rights to the green until it’s done. And a thread that is more important can raise its priority, asserting its right to play through.

The devil is in the details, of course, and those details have historically made threads difficult to use. Java makes creating, controlling, and coordinating threads much simpler. When creating a new thread is the best way to accomplish some task, it should be as easy as adding a new component to your application.

It is common to stumble over threads when you first look at them, because creating a thread exercises many of your new Java skills all at once. You can avoid confusion by remembering there are always two players involved in running a thread: a Java language object that represents the thread itself and an arbitrary target object that contains the method that the thread is to execute. Later, you will see that it is possible to play some sleight of hand and combine these two roles, but that special case just changes the packaging, not the relationship.

The Thread Class and the Runnable Interface

A new thread is born when we create an instance of the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
1 class. The
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 object represents a real thread in the Java interpreter and serves as a handle for controlling and synchronizing its execution. With it, we can start the thread, stop the thread, or suspend it temporarily. The constructor for the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 class accepts information about where the thread should begin its execution. Conceptually, we would like to simply tell it what method to run, but since there are no pointers to methods in Java, we can’t specify one directly. Instead, we have to take a short detour and use the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
4 interface to create an object that contains a “runnable” method. Runnable defines a single, general-purpose method:

public interface Runnable {  
    abstract public void run( );  
}

Every thread begins its life by executing the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method in the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 object (the “target object”) that was passed to the thread. The
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method can contain any code, but it must be public, take no arguments, have no return value, and throw no exceptions.

Any class that contains an appropriate

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method can declare that it implements the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 interface. An instance of this class is then a runnable object that can serve as the target of a new
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. If you don’t want to put the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method directly in your object (and very often you don’t), you can always make an adapter class that serves as the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 for you. The adapter’s
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method can call any method it wants to after the thread is started.

Creating and starting threads

A newly born

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 remains idle until we give it a figurative slap on the bottom by calling its
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method. The thread then wakes up and proceeds to execute the
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
6 method of its target object.
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 can be called only once in the lifetime of a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. Once a thread starts, it continues running until the target object’s
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
6 method returns. The
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method has a sort of evil twin method called
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
1 , which kills the thread permanently. However, this method is deprecated and should no longer be used. We’ll explain why and give some examples of a better way to stop your threads later in this chapter. We will also look at some other methods you can use to control a thread’s progress while it is running.

Now let’s look at an example. The following class,

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2, implements a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method to drive its drawing loop:

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}

To use it, we create a

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 object, passing it an instance of
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 as its target object, and invoke its
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method. We can perform these steps explicitly:

Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );

Here we have created an instance of our

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 class and passed it as the argument to the constructor for
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
8. When we call the
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method,
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
8 begins to execute
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2’s
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method. Let the show begin!

This situation is not terribly object-oriented. More often, we want an object to handle its own threads, as shown in , which depicts a

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 object that creates and starts its own
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. We’ll show our
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 class performing these actions in its constructor, although in practice it might be better to place them in a more explicit controller method (e.g.,
class Animation extends Thread {  
    ...  
    public void run( ) {  
        while (true ) {  
            // draw Frames  
            ... 
        }  
    }  
}
6):

Which of the following methods will start the thread public class Mythread?

Figure 8-1. Interaction between Animation and its thread

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}

In this case, the argument we pass to the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 constructor is
class Animation extends Thread {  
    ...  
    public void run( ) {  
        while (true ) {  
            // draw Frames  
            ... 
        }  
    }  
}
8, the current object (which is a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6). We keep the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 reference in the instance variable
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
8, in case we want to interrupt the show or exercise some other kind of control later.

The

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 interface lets us make an arbitrary object the target of a thread, as we did earlier. This is the most important general usage of the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 class. In most situations in which you need to use threads, you’ll create a class (possibly a simple adapter class) that implements the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 interface.

We’d be remiss not to show you the other technique for creating a thread. Another design option is to make our target class a subclass of a type that is already runnable. As it turns out, the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 class itself conveniently implements the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 interface; it has its own
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method, which we can override directly to do our bidding:

class Animation extends Thread {  
    ...  
    public void run( ) {  
        while (true ) {  
            // draw Frames  
            ... 
        }  
    }  
}

The skeleton of our

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 class looks much the same as before, except that our class is now a subclass of
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. To go along with this scheme, the default constructor of the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 class makes itself the default target. That is, by default, the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 executes its own
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
6 method when we call the
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method, as shown in . So now our subclass can just override the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method in the
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 class. (
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 itself defines an empty
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method.)

Which of the following methods will start the thread public class Mythread?

Figure 8-2. Animation as a subclass of Thread

Now we create an instance of

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 and call its
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method (which it also inherited from
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2):

Animation bouncy = new Animation("Bouncy");  
bouncy.start( );

Alternatively, we can have the

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 object start its thread when it is created, as before:

class Animation extends Thread {  
    ...  
    Animation (String name) {  
        start( );  
    }  
    ... 
}

Here our

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 object just calls its own
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method when an instance is created. (Again, it’s probably better form to start and stop our objects explicitly after they’re created, rather than starting threads as a hidden side effect of object creation.)

Subclassing

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 seems like a convenient way to bundle a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 and its target
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method. However, this approach often isn’t the best design. If you subclass
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 to implement a thread, you are saying you need a new type of object that is a kind of
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. While there is something unnaturally satisfying about taking an object that’s primarily concerned with performing a task and making it a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2, the actual situations where you’ll want to create a subclass of
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 should not be very common. In most cases, it will be more natural to let the requirements of your program dictate the class structure. If you find you’re subclassing
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 left and right, you may want to examine whether you are falling into the design trap of making objects that are simply glorified functions.

Finally, as we have suggested, we can build an adapter class to give us more control over how to structure the code. It is particularly convenient to create an anonymous inner class that implements

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 and invokes an arbitrary method in our object. This almost gives the feel of starting a thread and specifying an arbitrary method to run, as if we had method pointers. For example, suppose that our
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
2 class provides a method called
myThread = new Thread( ) {  
  public void run() { drawFrames( ); }  
}; 
myThread.start( ); 
                  
4, which performs setup (loads the images, etc.) and then starts a thread to perform the animation. We’ll say that the actual guts of the animation loop are in a private method called
myThread = new Thread( ) {  
  public void run() { drawFrames( ); }  
}; 
myThread.start( ); 
                  
5. We could use an adapter to run
myThread = new Thread( ) {  
  public void run() { drawFrames( ); }  
}; 
myThread.start( ); 
                  
6 for us:

class Animation {  
  
    public void startAnimating( ) {  
        // do setup, load images, etc. 
        ... 
 
        // start a drawing thread 
        myThread = new Thread ( new Runnable( ) {  
            public void run() { drawFrames( ); }  
        } ); 
        myThread.start( ); 
    } 
 
    private void drawFrames( ) { 
        // do animation ... 
    } 
}

In this code, the anonymous inner class implementing

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6 is generated for us by the compiler. We create a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 with this anonymous object as its target and have its
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
6 method call our
myThread = new Thread( ) {  
  public void run() { drawFrames( ); }  
}; 
myThread.start( ); 
                  
6 method. We have avoided implementing a generic
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method in our application code, but at the expense of generating an extra class.

Note that we could be a bit more terse in the previous example by simply having our anonymous inner class extend

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 rather than implement
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
6:

myThread = new Thread( ) {  
  public void run() { drawFrames( ); }  
}; 
myThread.start( ); 
                  

We have seen the

Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5 method used to bring a newly created
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2 to life. Several other instance methods let us explicitly control a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2’s execution:

  • The

    try {  
    	// static convenience method
        Thread.sleep( 1000 );  
        // instance method
        sleep( 500 );
    }   
    catch ( InterruptedException e ) {  
        // someone woke us up prematurely 
    }
    7 method causes the current thread to wait for a designated period of time, without consuming much (if any) CPU time.

  • The

    try {  
    	// static convenience method
        Thread.sleep( 1000 );  
        // instance method
        sleep( 500 );
    }   
    catch ( InterruptedException e ) {  
        // someone woke us up prematurely 
    }
    8 method wakes up a thread that is sleeping or is otherwise blocked on a long I/O operation.[]

  • The methods

    try {  
    	// static convenience method
        Thread.sleep( 1000 );  
        // instance method
        sleep( 500 );
    }   
    catch ( InterruptedException e ) {  
        // someone woke us up prematurely 
    }
    9 and
    class Animation implements Runnable {  
       ...  
       public void run( ) {  
           while ( true ) {  
               // draw Frames  
               ... 
           }  
       }  
    }
    00 coordinate the execution of two or more threads. We’ll discuss them in detail when we talk about thread synchronization later in this chapter.

We should also mention that there are three deprecated thread control methods:

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
01 ,
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
02, and
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
03 . The
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
01 method complements
Animation happy = new Animation("Mr. Happy");  
Thread myThread = new Thread( happy );  
myThread.start( );
5; it destroys the thread.
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
06, and the deprecated
class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
1 method can be called only once in the life cycle of a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2. By contrast, the deprecated
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
09 and
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
10 methods were used to arbitrarily pause and then restart the execution of a
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
2.

Although these deprecated methods still exist in the latest version of Java, they shouldn’t be used in new code development. The problem with both

class Animation implements Runnable {  
    Thread myThread;  
    Animation (String name) {  
        myThread = new Thread( this );  
        myThread.start( );  
    }   
    ... 
}
1 and
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
09 is that they seize control of a thread’s execution in an uncoordinated and harsh way. This make programming difficult—it’s not always easy for an application to anticipate and properly recover from being interrupted at an arbitrary point in its execution. Moreover, when a thread is seized using one of these methods, the Java runtime system must release all of its internal locks used for thread synchronization. This can cause unexpected behavior and, in the case of
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
09, can lead to deadlock situations.

A better way to affect the execution of a thread—which requires just a bit more work on your part—is by creating some simple logic in your thread’s code using monitor variables ( flags), possibly in conjunction with the

try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}
8 method, which allows you to wake up a sleeping thread. In other words, you should cause your thread to stop or resume what it is doing by asking it to nicely, rather than by pulling the rug out from under it unexpectedly. The thread examples in this book will use this technique in one way or another.

We often need to tell a thread to sit idle, or “sleep,” for a fixed period of time. While a thread is asleep, or otherwise blocked on input of some kind, it shouldn’t consume CPU time or compete with other threads for processing. For this, we can either call the thread’s

try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}
7 instance method or use the static convenience method
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
17. Either way, the call causes the currently executing thread to delay for a specified number of milliseconds:

try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}

In either case,

try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}
7 throws an
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
19 if it is interrupted by another Thread via its
try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}
8 method. As you see in the previous code, the thread can catch this exception and take the opportunity to perform some action—such as checking a variable to determine whether or not it should exit—or perhaps just perform some housekeeping and then go back to sleep.

Finally, if you need to coordinate your activities with another thread by waiting for the other thread to complete its task, you can use the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
00 method. Calling a thread’s
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
00 method causes the caller to block until the target thread dies. Alternatively, you can poll the thread by calling
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
00 with a number of milliseconds to wait. This is a very coarse form of thread synchronization. Later in this chapter, we’ll look at a much more general and powerful mechanism for coordinating the activities of threads:
try {  
	// static convenience method
    Thread.sleep( 1000 );  
    // instance method
    sleep( 500 );
}   
catch ( InterruptedException e ) {  
    // someone woke us up prematurely 
}
9 and
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
25.

A thread continues to execute until one of the following things happens:

  • It explicitly returns from its target

    class Animation implements Runnable {  
       ...  
       public void run( ) {  
           while ( true ) {  
               // draw Frames  
               ... 
           }  
       }  
    }
    5 method.

  • It encounters an uncaught runtime exception.

  • The evil and nasty deprecated

    class Animation implements Runnable {  
        Thread myThread;  
        Animation (String name) {  
            myThread = new Thread( this );  
            myThread.start( );  
        }   
        ... 
    }
    1 method is called.

So what happens if none of these things occurs and the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
5 method for a thread never terminates? The answer is that the thread can live on, even after what is ostensibly the part of the application that created it has finished. This means we have to be aware of how our threads eventually terminate, or an application can end up leaving orphaned threads that unnecessarily consume resources.

In many cases, we really want to create background threads that do simple, periodic tasks in an application. The

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
29 method can be used to mark a Thread as a daemon thread that should be killed and discarded when no other application threads remain. Normally, the Java interpreter continues to run until all threads have completed. But when daemon threads are the only threads still alive, the interpreter will exit.

Here’s a devilish example using daemon threads:

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
0

In this example, the

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
30 thread sets its daemon status when it is created. If any
class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
30 threads remain when our application is otherwise complete, the runtime system kills them for us. We don’t have to worry about cleaning them up.

Daemon threads are primarily useful in standalone Java applications and in the implementation of the Java runtime system itself, but not in applets. Since an applet runs inside of another Java application, any daemon threads it creates could continue to live until the controlling application exits—probably not the desired effect. A browser or any other application can use

class Animation implements Runnable {  
   ...  
   public void run( ) {  
       while ( true ) {  
           // draw Frames  
           ... 
       }  
   }  
}
32 to contain all of the threads created by subsystems of an application and then clean them up if necessary.

Which of the following methods will start this thread public class?

start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread.

Which method is used to start the thread?

The start() method of thread class is used to begin the execution of thread. The result of this method is two threads that are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

Which of the following methods will start this thread public class Mythread implements runnable?

Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be executed. start() method is used to begin execution of the thread that is execution of run().

Which of the following will create and start this thread?

which of these will create and start this thread? [A]. new Runnable(MyRunnable). start();