Wednesday, February 10, 2016

Threads in Java


Hi guys, After a long time I'm here with a new post. In this post I gonna talk about a most important core section in Java. It is about Threads. This is a huge concept. I'm gonna just touch it in this post and this is extremely simple to understand for beginners. Lets move.  

What is multitasking ?


Multitasking is the way of executing several tasks  simultaneously. Normally we describe two types of multitasking. 
  1. Process based
  2. Thread based

Process based multitasking


Process based multitasking is "Executing several tasks simultaneously where each task is a separate independent process". This is Operating System level concept. In this section I'm not going to talk about this. But let me explain a bit. 


Just think you are doing any Java project using Eclipse. Then you open any media player and play music that you like. Now you an understand there are two separate processes except other background processes(WiFi, Virus guard...etc )


Thread based multitasking


This is very important for us. I can define it, "Executing several tasks simultaneously where each tack in a same program is called thread based multitasking". This is programming level concept, so we can touch with it.


What is a Thread ?

Thread is a flow of execution. For an example, simply if you are running a Hello world program, it is just a one thread which is running on the main thread.


public class ThreadDemo{
 
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}


How to implement Thread based multitasking in Java ?

We can create threads in two ways in Java. 
  1. Extending Thread class
  2. Implementing Runnable interface


Create Threads by extending Thread class

This is very simple, right ! Don't confuse about threads. Here I'm going to explain, how to create two threads running simultaneously by extending Thread class. There are few steps.

  1. Define a Thread
  2. Instantiate the Thread
  3. Start the Thread 

Think you want to print your name 10 times and print 0 to 10 numbers simultaneously. This is your task. Very simple.

So there are two threads that you need to create. 
  1. One thread to print your name
  2. Another one to print number

You know that you need to have main method to run any application (Don't think about static initialization block at this time). Main method is responsible to run the main Thread. Because without main thread, we cannot run any program. So I'm going to print name in the main method(Just like hello world program).

Step 01

public class ThreadDemo{
 
    public static void main(String args[]){

        for (int i=0; i<10; i++) {
            System.out.print("Your name"); 
        }
    }
}

If you run this program you can see, your name 10 times. At the time the are only one thread. Then I create another class to print 0 to 10 numbers. And I extend it to Thread class as below. It means I initialize a new Thread.

Step 02

public class Demo extends Thread{
 
}


At the time there are two threads. Next step is override the run() method.

What is run( ) method ?


Your business logic goes here. Simply your task is implemented here. This method provides the mechanism to enter to the thread. 


Step 03

public class Demo extends Thread{
    public void run(){
  
    }
}


Then you need to put your business logic (job) in run() method. In here I want to print 0 to 10 numbers. 


Step 04

public class Demo extends Thread{
    public void run(){
        for (int i=0; i<10; i++) {
            System.out.print(i); 
        }
    }
}


So now we created two threads. But how to run it ? It is simple, just create the instance of Demo class which is implemented run() method. Then we can start the thread using start() method.


Step 05

public class ThreadDemo{
 
    public static void main(String args[]){

        Demo demo = new Demo();
        demo.start();

        for (int i=0; i<10; i++) {
            System.out.print("Your name"); 
        }
    }
}

After the demo.start() statement there are two threads, main thread(ThreadDemo) and child thread(Demo).

When you run this program, sometimes you may not able to see any different. Because your processor is too speed. If you cannot see any different, please run it again and again. Then you may see mixing your name and the number. It means your program runs two threads at same time.


Create Threads by implementing Runnable interface

This is also same as what I did above. But in this time I'm not going to extend the Demo class to Thread class, instead of that I implement that class to Runnable interface. It look like this.


public class Demo implements Runnable{
    public void run(){
        for (int i=0; i<10; i++ ) {
            System.out.print(i); 
        }
    }
}


Then you have to do some changes in main method.

public class ThreadDemo{
 
    public static void main(String args[]){

        Demo demo = new Demo();
        Thread t = new Thread(demo);
        t.start();

        for (int i=0; i<10; i++) {
            System.out.print("Your name"); 
        }
    }
}

You can see what I've done.

  • Create an instance of Demo class
  • Create an instance of Thread class and specify the target run() method by passing demo into Thread class. 

This is a very simple and basic level of explanation about threads in Java. Hope you understood the basics. Bye.

Users of multi-threading

  • For video games
  • Animations
  • Run background processing 
  • Get the advantage of multi core processors 
  • Used in servlets 


Advantages of multi-threading

  • Get the full usage of system resources
  • improved performances 


Disadvantages of multi-threading

  • Complexity of developing multi threaded applications
  • Difficult to debug and test
  • Potential of dead locks