Create and use threads

Two ways to create thread:

1) Extending thread class

Example 1:

Example 2:

2) Implement interface Runnable

Example 1:

Problem 1 :

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?

class SingAndDance3 {
    public static void main(String args[]) {
        Thread sing = new Sing();
        Thread newThread = new Thread(sing);
        newThread.start();
    }
}
class Sing extends Thread{
    public void run() {
        System.out.println("Singing"); 
    } 
}

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().

Last updated