Monday 12 May 2014

Creating Threads in JAVA

Introduction to multithreading

Thread Creation

We can Create threads in Java by using the following two ways.
  1. By Extending Java.lang.Thread class.
  2. By implementing the Java.lang.Runnable interface.
  1. Create thread by extending Thread class
  • The class should extend Java Thread class.
  • The class should override the run() method.
  • The functionality that is expected by the Thread to be executed is written in the run() method.
Example:

class MyThread  Extends  Thread{
          Public Void run(){
     system.out.println("thread started running.....");
                                   }
}


class MyThreadDemo{
       
             Public Static void main(String srgs[]){
                            MyThread obj=new MyThread();
                               obj.start();
                           }
}


2.Create Thread by implementing Runnable interface



    • Other way of creating a thread is to create a class that implements the Runnable interface. We must need to give the definition of run() method.This run method is the entry point for the thread and thread will be alive till run method finishes its execution.
    • Once the thread is created it will start running when start() method gets called. Basicallystart() method calls run() method implicitly.

      Example:

      class MyThread  implements Runnable{
                Public Void run(){
           system.out.println("thread started running.....");
                                         }
      }

      class MyThreadDemo{
           
                   Public Static void main(String srgs[]){
                                  MyThread obj=new MyThread();
                                    Thread t1=new Thread(obj);
                                     t1.start();
                                 }
      }

      No comments:

      Post a Comment

      test