Wednesday, August 11, 2010

Multithreading: MyRunnable.java

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

The following block of code creates a Thread using a Runnable target:
Runnable target = new MyRunnable();
Thread myThread = new Thread(target);

Which of the following classes can be used to create the target, so that the preceding code compiles correctly?

  1. public class MyRunnable extends Runnable{public void run(){}}

    Incorrect because interfaces are implemented, not extended.


  2. public class MyRunnable extends Object{public void run(){}}

    Incorrect because even though the class has a valid public void run() method, it does not implement the Runnable interface.


  3. public class MyRunnable implements Runnable{public void run(){}}

    Correct. The class implements the Runnable interface with a legal run() method.


  4. public class MyRunnable implements Runnable{void run(){}}

    Incorrect because the run() method must be public.


  5. public class MyRunnable implements Runnable{public void start(){}}

    Incorrect because the method to implement is run(), not start().


No comments:

Post a Comment