Creating Threads in Java
Creating Threads in Java
com
info@wscubetech.com
2
www.wscubetech.com
How we create thread?
Class Interface Thread class provide constructors and methods
to create and perform operations on a
Object Runnable thread.Thread class extends Object class and
implements Runnable interface.
3
www.wscubetech.com
Definition of Thread Class
5
www.wscubetech.com
Example
class test extends Thread{ Output :
public void run(){
System.out.println("thread is running"); thread is running
}
public static void main(String args[]){
test t1=new test();
t1.start();
Starting a thread:
} start() method of Thread class is used to start a
} newly created thread. The thread moves from New
state to the Runnable state. When the thread gets a
chance to execute, its target run() method will run.
6
www.wscubetech.com
Definition of Runnable Interface
7
www.wscubetech.com
Thread creation by implementing the Runnable Interface
8
www.wscubetech.com
Example
9
www.wscubetech.com
Differences Between Thread and Runnable
a) Each thread created by extending the Thread class creates a unique object for
it and get associated with that object. On the other hand, each thread created
by implementing a Runnable interface share the same runnable instance.
b) As each thread is associated with a unique object when created by extending
Thread class, more memory is required. On the other hand, each thread
created by implementing Runnable interface shares same object space hence,
it requires less memory.
c) If you extend the Thread class then further, you can inherit any other class as
Java do not allow multiple inheritance whereas, implementing Runnable still
provide a chance for a class to inherit any other class.
10
www.wscubetech.com
Differences Between Thread and Runnable
a) One must extend a Thread class only if it has to override or specialise some
other methods of Thread class. You must implement a Runnable interface if
you only want to specialise run method only.
b) Extending the Thread class introduces tight coupling in the code as the code of
Thread and job of thread is contained by the same class. On the other hand,
Implementing Runnable interface introduces loose coupling in the code as the
code of Thread is seprate from the job assigned to the thread.
11
www.wscubetech.com
Conclusion
12
www.wscubetech.com
www.wscubetech.com
info@wscubetech.com
Thank You
https://www.facebook.com/wscubetech.india https://www.linkedin.com/company/wscube-tech
https://plus.google.com/+wscubetechjodhpur https://www.youtube.com/c/wscubetechjodhpur
https://twitter.com/wscube