Friday, September 10, 2010

Code to Understand Objective 4.1

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)

4.1 Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.

Extending java.lang.Thread


/*
The simplest way to define code to run in a separate thread is to

-Extend the java.lang.Thread class.
-Override the run() method.

Limitation for extending Thread is you can’t extend anything else. And it’s not as if you really need that inherited Thread class behavior, because in order to use a thread you’ll need to instantiate one anyway.

*/









Overloaded run() Method


/*
Keep in mind that you’re free to overload the run() method in your Thread subclass.

The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself.
*/





 
 
 
 
 
Implementing java.lang.Runnable

/*
Implementing the Runnable interface gives you a way to extend any class you like, 
but still define behavior that will be run by a separate thread. 
*/

















Instantiating and Starting a Thread

/*
Code demonstrates how to INSTANTIATE and START thread
*/




















getName() to Print the Executing Thread

/*
Code demonstrates how diplay name of Thread running
*/



 











/*
Code demonstrates how diplay name of main Thread running
*/



 
 
 
Starting and Running Multiple Threads
/*
We already had two threads, because the main() method starts in a thread of its own, and then t.start() started a second thread. Now we’ll do more. The following code creates a single Runnable instance and three Thread instances. All three Thread instances get the same Runnable instance, and each thread is given a unique name. Finally, all three threads are started by invoking start() on the Thread instances.
*/

No comments:

Post a Comment