Thursday 20 February 2014

Multi-threading??? Say what..!?

Let me explain what is Multi-threading.

Assume you have a simple Java class with a method to add two numbers.

public void addNum(int a, int b){

......

}

Lets say person "A" wants to execute this program to add two number. We know that is possible!

Lets say person "B" also wants to execute this program. Here we have 2 different scenarios

1. B can execute after A finishes execution - This is sequential execution
2. B can make another copy of this program and execute on a different machine - This is parallel execution

But how can "B" execute this program in parallel, but without making duplicate copies of this program.

This is were Multi-Threading comes into picture
Multi-Threading allows parallel execution of a program without creating multiple copies of that program.

Multithreading is a process of executing multiple threads simultaneously. A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process. So in short, Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system.

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.

A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

 Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time. 

For example, look at the diagram shown as:



In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread.

Advantages of multithreading over multitasking :  

    Reduces the computation time.
    Improves performance of an application.
    Threads share the same address space so it saves the memory.
    Context switching between threads is usually less expensive than between processes. 
    Cost of communication between threads is relatively low.