This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Hi All there are few questions from Khaalid Mock Exam Since answers are not provided I would be thnakful if you give your views Given that a static method doIt() in a class Work represents work to be done, what block of code will succeed in starting a new thread that will do the work? CODE BLOCK A: Runnable r = new Runnable() { public void run() { Work.doIt(); } }; Thread t = new Thread(r); t.start(); CODE BLOCK B: Thread t = new Thread() { public void start() { Work.doIt(); } }; t.start(); CODE BLOCK C: Runnable r = new Runnable() { public void run() { Work.doIt(); } }; r.start(); CODE BLOCK D: Thread t = new Thread(new Work()); t.start(); CODE BLOCK E: Runnable t = new Runnable() { public void run() { Work.doIt(); } }; t.run(); a.Code block A b.Code block B c.Code block C d.Code block D e.Code block E
Only b is correct according to me as we cannot instaniate an Interface what fo you all say ?
SCJP,SCWCD,SCBCD<br />If Opportunity doesn't knock then build the door
Yes, this will work. Here, we are creating an anonymous class implementing the Runnable interface. Note the run method that has been implemented which calls the Work.doIt(). Hence the thread will execute the doIt method.
Nope. This will not work. When you implement a thread by extending the Thread class, you are required to override the run() method and not the start method. I know one might argue because we have an overridden version of start() method here, t.start will execute Work.doIt(). But the catch is, it will be just a normal synchronous method invocation, and it will not start a new thread of execution.
Nope. This answer will trick you into thinking it might be the right one. Look carefully - though we are implementing a Runnable interface, you are not creating a new Thread object. Runnable only defines the run() method and hence this code will not even compile!
Nope. Wrong syntax. We don't know if Work extends thread, and even if it does, we only know it contains a static method doIt(). We are not sure if it implements the run() method. Too many things to assume.....
Nope. This is not the correct way of starting a new thread. Though the first part of setting up the run method is done correctly here, note that no thread objects are created! Hope this helps. If not, feel free to ask for more
Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).