Java Threads

Lets say we want our java program to run multiple tasks concurrently, how will we accomplish this ? Well, the answer is “threads“, threads run concurrently with other threads.

class ThreadEx extends Thread

class ThreadEx implements Runnable

In order to create threads we have to extend the “Thread” class or implement “Runnable” interface. Well what’s the difference? Remember that in java we can’t extend from a class more than once, so we wouldn’t be able to have two classes extending from “Thread”. We can accomplish this by implementing the runnable class, allowing other classes to create threads.

//Not Possible
class ThreadEx1 extends Thread{
}

class ThreadEx2 extends Thread{
}

//Allowed
class ThreadEx1 implements Runnable{

}

class ThreadEx2 implements Runnable{

}

Next, thing we need to do is override the run() method from the thread class. The run() method run’s everything as a thread.

class ThreadEx extends Thread{
   //Override the run()
   void run(){
     for(int i=0; i<=10; i++){
         System.out.println("Thread id: "+Thread.currentThread.getId());
         System.out.println(i);
         Thread.sleep(1000);
     }
   }
}

We override the run method and the current thread will print its id and count from 0-10, while sleeping for 1 second for each iteration.

Let’s instantiate ThreadEx and create 3 threads.

Public static void main(String[] args){
      Thread t1= new ThreadEx();
      Thread t2= new ThreadEx();
      Thread t3= new ThreadEx();

      t1.start();
      t2.start();
      t3.start();
}

Then we call start() method to run the threads

Leave a comment

Design a site like this with WordPress.com
Get started