Multithreading in Java

All computer operating systems allow us to perform multiple tasks at the same time. i.e. take notes in a notepad, IM, email, etc. Similarly, multithreading is doing multiple things within a program.

Multithreading means multiple threads. Thread defines a separate path of execution in a program.
A multithreaded program is one that contains two or more threads that run simultaneously.

Multitasking involves multiple processes. Now every process has its own memory space. While in case of multithreading, all threads share the same memory space of the process in which they reside.
Interprocess communication is expensive while interthread communication is cheaper.

Lifecycle of a thread :

Image result for thread lifecycle


The above diagram shows the lifecycle of a thread in Java.

Thread has 5 states :
1. New - new thread created
2. Runnable - ready to run
3. Running - in running state
4. Blocked - in waiting state
5. Dead - execution completed

All Java programs have a main thread of execution that starts with the program. The main thread is important as :
1. Other child threads are spawned from this thread.
2. It is the last thread to complete execution alongwith shutdown actions of the program.

You can check the main thread of your program by using :

Thread t = Thread.currentThread();

System.out.println(t.getName() + " " + t.getState());

An example with the above can be found here


Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures