C
C
Core Java
Search…
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?
1
class SingAndDance3 {
2
public static void main(String args[]) {
3
Thread sing = new Sing();
4
Thread newThread = new Thread(sing);
5
newThread.start();
6
}
7
}
8
class Sing extends Thread{
9
public void run() {
10
System.out.println("Singing");
11
}
12
}
Copied!
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 modified 2yr ago