Sunday, 28 July 2013

Multi Threading

This blog explains basic principles of Java Threading and how to create a multi-threaded application.

Threads are programs that run simultaneously. A very practical example would be the situation where a user is watching a movie and at the same time downloading something from the Internet. Here video player and Internet down-loader are 2 threads running simultaneously.

Java provides three ways to create Threads. That's right. There are three ways of creating Thread and not two.


  1. Extend Thread class
  2. Implement Runnable interface
  3. Implement Callable interface
1. Extend Thread Class

package com.hunaid.thread;

public class MyThread extends Thread{

 public void run(){
  System.out.println("MyThread run called");
  for(int i=0;i<=5;i++){
   System.out.println(i);
  }
 }
}

Here we have created a class which is extending Thread class. We have also implemented a method called run(). This is the method in which the logic should come which needs to run simultaneously with other Threads.


package com.hunaid.thread;

public class ThreadTest {

 public static void main(String args[]){
  MyThread myThread = new MyThread();
  myThread.start();
  System.out.println("In Main after starting MyThread");
 }
}

Here we have created a instance of MyThread class and called the method start() on it.
This will bring the thread MyThread from new to runnable state. And most probably start the thread instantly. The reason I mentioned most probably is that it is up to the JVM to move the thread from runnable to running state. So if we assume that the thread will start instantly on calling start() method. The output will be as
MyThread run called
0
1
2
3
4
5
In Main after starting MyThread

The text 'In Main after starting MyThread' could be printed anywhere between 0 to 5. That is because while the thread MyThread is running JVM could decide to give the main thread that is main() method the execution slot.

In the next chapter lets see how to implement thread with Runnable interface.


Thread class >> Runnable Interface >> Callable Interface  >> CountDownLatch  >> CyclicBarrier

No comments:

Post a Comment

Share the post