MultiThreading in Java

What is Multitasking?

Multitasking is executing multiple tasks simultaneously.
Example: Class room student. At a time he can perform multiple tasks like listening to class,taking notes,mobile checking,sleeping :), staring cute girls etc.

In Java, Multitasking is of two types

  • Process based multitasking
  • Thread based multitasking

Process based multitasking

Executing several tasks simultaneously where each task is a separate independent program(process).

Example:

  • Writing java program in editor
  • Listening music
  • Download file from internet

Here,each each task is a separate program which performed simultaneously.

Note: It is suitable in OS level not in programatic level.

Thread based multitasking

Executing several tasks simultaneously where each task is a separate independent part of a same program and each independent part is called Thread.

Example:
Lets say we have a program having Program(10k Line of code) and we are executing the sequentially though they are independent code.

As the program having two independent code i.e not related to each other we can divide the one program into two independent part(Thread) and execute parallelly.
Now the code is taking 5-6 hour instead of 10 hour.

Note:
  • Thread Based Multitasking is suitable in programatic level.
  • All the thread use the same address space because all belongs to one program(process).

Another thread Example

Search some key words in the files in the system. Lets say keywords are java,spring,hibernate.

First without using threading,it will take 50 hr(assume). Because we have to search in the C:\ drive, then D:\,then E:\ and so on.

If we will go with threading i.e one thread for C:\ drive search and another thread for D:\ and so on then searching will take less time.

Again we can do the same in each drive i.e create Thread for each folder in the drive itself,again time will reduce.

Still we have a chance to reduce time i.e in each folder, create separate threads for each files.

By using above threading concept, we will achieve the searching in maximum 15 min. So we come from 50 hr to 15 min. That is the thread concept.