# Create and use threads

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvRgkpizyRE0pdNqge%2Fimage.png?alt=media\&token=3423e6c2-fb24-424f-baed-d22120efba29)

## Two ways to create thread:

### 1) Extending thread class

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvSo75UIZY-CYqSzlM%2Fimage.png?alt=media\&token=463330af-64ac-4c00-95ce-d7ac98005eed)

#### Example 1:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvSvRarBA0PRppgx6-%2Fimage.png?alt=media\&token=8bf9b069-7194-4c46-9e85-204d5d997c8d)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvSzDR-eo9fgaT0nuM%2Fimage.png?alt=media\&token=3c4a439e-a72b-4fd0-9c18-4ac3471f64a7)

#### Example 2:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvUqaox6hWW8JquGwr%2Fimage.png?alt=media\&token=86a03905-a08a-4586-8888-e6908b54d9ef)

### 2) Implement interface Runnable

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvV1bHXqsHMOvwfWt3%2Fimage.png?alt=media\&token=e010ca48-532e-45e3-9e85-e5e4aeb7e47c)

#### Example 1:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTvQqwQur99VVjwRi1Z%2F-LTvV5x425Jl17qDMpmA%2Fimage.png?alt=media\&token=eece681f-4bc0-42a6-b035-66f59d20fdb0)

#### 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?

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

