There are two ways to create a thread:
- By extending Thread class
- By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface. |
Commonly used Constructors of Thread class:
|
Commonly used methods of Thread class:
|
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). |
|
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
|
1)By extending Thread class:
Output:thread is running...
Who makes your class object as thread object?
Thread class constructor allocates a new thread object.When you create object of Multi class,your class constructor is invoked(provided by Compiler) from where Thread class constructor is invoked(by super() as first statement).So your Multi class object is thread object now. |
2)By implementing the Runnable interface:
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute. |
No comments:
Post a Comment