Thursday, July 11, 2013

1. How to create thread in Java ?


There are two major ways to create a thread in Java namely,

1. By inheriting or "extending" the thread class
2. By implementing the runnable interface

In both the above ways one has to implement the run() method

Examples

1. By inheriting or "extending" the thread class

public class myClassWithThread extends Thread
{
     public void run()
     {
/* Put your implementations of the
  thread functionality here */
     }
}

public static void main(String args[])
{
     myClassWithThread MyThreadObj = new myClassWithThread ();

     myClassWithThread.start();
}

2. By implementing the runnable interface

public class myClassWithThread implements Runnable
{
public void run()
{
/* Put your implementations of the
       thread functionality here */
}
}

public static void main(String args[])
{
     Thread myThread = new Thread (myClassWithThread);

     myThread.run();
}


No comments :

Post a Comment