Create and use threads
Last updated
Last updated
Class SingAndDance instantiates a thread by passing it an instance of the class that extends the thread itself. Will the following class execute method start() or run() twice? What do you think is the output of the following code?
Purpose: When you instantiate a thread, say, A, passing it another Thread instance, say, B, calling A.start() will start one new thread of execution. Calling A.start() will execute B.run.
Explanation: Class Thread defines an instance variable target of type Runnable, which refers to the target object it needs to start. When you instantiate newThread by passing it a Sing instance, sing, newThread.runnable refers to sing. When you call newThread.start(), newThread() checks if its target is null or not. Because it refers to sing, calling newThread.start() starts a new thread of execution, calling target.run().