8/8/17

Creating and Running Threads

There are two ways you can create threads

  1. By extending Thread class from java.lang package
  2. By Implementing Runnable interface
Lets explore these methods one by one

By extending Thread class


Extend thread class in your public class and override run method from Thread class. "run" method is job that will be executed by all your threads. Next is to crate as many threads as you want, give them a name (optional but useful to give names) and finally start them. 

You can not start a thread twice, you will get java.lang.IllegalThreadStateException at runtime.



package com.techiekunal.examples;

public class ThreadClassExample extends Thread{

 @Override
 public void run() {
  System.out.println("Executing Job. by thread :- " + Thread.currentThread().getName());
 }
 
 public static void main(String[] args) {
  
  // Creating new threads
  ThreadClassExample t1 = new ThreadClassExample();
  ThreadClassExample t2 = new ThreadClassExample();
  
  // Setting name for threds
  t1.setName("Bruno");
  t2.setName("Adam");
  
  // Starting threads
  t1.start();
  t2.start();
  
 }
}


By Implementing Runnable interface

Runnable interface gives you run method to override. Give your job logic inside run method.
Now in your public class create Threads by passing instance of Runnable implementation class


package com.techiekunal.examples;

class RunnableImpl implements Runnable {

 @Override
 public void run() {
  System.out.println("Job Executed by thread :- " + Thread.currentThread().getName());
 }
 
}

public class RunnableInterfaceExample {
 
 public static void main(String[] args) {
  RunnableImpl runnableImpl = new RunnableImpl();
  Thread t1 = new Thread(runnableImpl,"Bruno");
  Thread t2 = new Thread(runnableImpl,"Adam");
  
  t1.start();
  t2.start();
 }
}

Threads will be stopped after they finish executing run method.