java Thread creation

What is a thread and how to create a thread in java ?

Thread :
A Thread is a part of program that is a program can contain more than one thread which have separate path of
execution in memory and can work more than one task simultaneously.
A thread can create two way in java :

  • By extending Thread class
  • By implementing Runnable interface

By extending Thread class :
In this way you will simply extends Thread class and override its run() method after that just create object of main class
in main() method and call start() method. You can better understand with below example.


package com.pkjavacode.com;

public class ThreadExample extends Thread {
public void run() {
System.out.println("Run method executing...");
}

public static void main(String arg[]) {
ThreadExample t = new ThreadExample();
t.start();

}
}

 

Output :
Run method executing…

 

By implementing Runnable interface :

In this way you will simply implements Runnable interface and override its run() method after that just create object of
main class in main() method and create Thread class object and pass main class object into Thread constructor and call
start() method. You can better understand with below example.


package com.pkjavacode.com;

public class ThreadExample implements Runnable {
public void run() {
System.out.println("Run method executing...");
}

public static void main(String arg[]) {
ThreadExample te = new ThreadExample();
Thread t=new Thread(te);
t.start();

}
}

 

Output :

Run method executing…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s