What are the ways in which a thread is created in Java?



There are two ways to create a new thread of execution.

By Implementing a Runnable Interface

One way to create a thread is by implementing the Runnable interface to do so −

  • Create a class and implement the Runnable interface.
  • Override the run() method of the Runnable interface.
  • Instantiate the Thread class by passing the object of the current class (a class that implements the Runnable interface) to its constructor.
  • Once a Thread object is created, you can start it by calling start() method, which in turn executes a call to run() method.

Example

class first implements Runnable {
   public void run(){
      try {
         for(int i=0;i<=20;i+=2) {
            Thread.sleep(600);
            System.out.println(i);
         }
      } catch(Exception e) {
   }
}

class MyThreadd {
   public static void main(String args[]) {
      first obj = new first();
      Thread thread = new Thread(obj);
      thread.setPriority(Thread.MAX_PRIORITY);
      thread.start();
      System.out.println(thread.isAlive());
   }
}

Output

true
0
2
4
6
8
10
12
14
16
18
20
Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician


Advertisements