How to create thread in java

Create thread using Runnable Interface


Runnable interface has following specification. It has a abstract method run(). On execution of thread, it execute run() method. So code written in run() method will be executed by newly created thread.

public interface Runnable
 {
  void run();
 }

If programmer is not concerned with control over thread execution then runnable interface is implemented to create thread. After implementation run() method has to be defined.




Step 1 Implement runnable interface and define run method()

Create a class by implementing runnable interface and provide definition for run() method. Let's assume we want this new thread to perform some large calculation. In that case we will write that code in run() method.

Syntax :

class one implements Runnable 
 {
 public void run()
   {
     System.out.println("Thread running...");
   }
 }

Step 2 Create object of Thread class

Create object of Thread class. Thread class has following constructor

  • Thread(Runnable r )
    This constructor needs one Runnable object as argument.

  • Thread (Runnable r, String name)
    This constructor has two parameter. String parameter passed as second parameter will be set as name of thread.

Syntax :

// Using first constructor
Thread th=new Thread(new one());

// Using second constructor
Thread th1=new Thread(new one(), "My-Thread");

Step 3 Call start() method

Finally call start() method. On invocation of start() method a new thread will be created and this thread will execute run() method. Call to start() method is asynchronous which means call to start() method will return immediately.

Syntax :

// Create new thread and start execution
th.start();


Complete Program for multithreading

Following program is having two threads in it. These threads will be running concurrently. Thread scheduling is not predictable. Output of following program is not fixed. It will vary with every execution.

class one implements Runnable 
{
  public void run()
   {
    for(int i=0;i<10;i++)
	 System.out.println("New Thread:"+i);
   }
 }
 class two
 {
  public static  void main(String arg[])
   {
     one ob=new one(); 
     Thread th=new Thread(ob);
	 th.start();
	 
	 // This loop executed by Main Thread
	 for(int i=0;i<10;i++)
	 System.out.println("Main Thread:"+i);
	 
   }  
} 



Review Questions
Connection Error: