❮ Previous Next ❯

How To Create And Run A Thread:

We know that always a main thread is available in a java program. Apart this we can create our own thread and execute it also. There are two ways to create a thread :

By extending from Thread class:

When start() method is invoked by object obj, then thread starts it's execution on the object of MyThread. That means it will execute the statements inside the run() method.

Let's see a program for better understanding.

Example

class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("child thread");
}
} }
class ThreadDemo1
{
public static void main(String args[])
{
MyThread obj=new MyThread();
//thread instantiation obj.start();
//start the thread for(int i=1;i<=5;i++)
{
System.out.println("main thread");
}
}
}
Output:

main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread

Here the definition of MyThread class is representing a thread and the body of the run() method is representing a job. When main() is declared, main thread is created. main thread is responsible to instantiate the MyThread object. When start() method is invoked then thread MyThread will start its execution, that means run() method will be executed. After invoking start() method the for loop execution is the responsibility of main thread.

❮ Previous Next ❯


  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved