Introduction to Threads

Thread is a lightweight process which has its own call stack.
We use threads to achieve unit of work.

Threads in java can be said as below


1) Instance of java.lang.Thread class

  1. Thread t1 = new Thread();
Thread t1 = new Thread();

Instance of Thread or object of Thread is similar to any other object In Java which has both state(variables) and behaviour(methods).

It lives and also dies in heap.

2) Separate thread of execution

  1. t1.start();
t1.start();


Thread of execution is a separate lightweight process which has its own call stack.

Every thread has its memory cache but they can access the shared data of other threads.

When a JVM starts up, there is usually a single non-daemon main thread exists which typically calls the main method.

We can write code to start other threads as per our requirement.

JVM allows an application to have multiple threads of execution running concurrently, we call it is multithreading.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.

Thread (capital ‘T’) is a java class which is used to create the Thread.

It has methods for starting a thread,joining threads etc.

Thread runs on a separate call stack

Each and every new thread runs in a separate call stack.

As we learned that main method is called by JVM by creating a separate thread, It will run in a separate call stack.

  1. Public static void main(String[] args){
  2. ...............
  3. }
Public static void main(String[] args){
...............
}


thread_main_diag.jpg

main thread starts a new thread as below

  1. Public static void main(String[] args){
  2. Runnable r = new MyThread();
  3. Thread t = new Thread(r);
  4. t.start();
  5. }
Public static void main(String[] args){
Runnable r = new MyThread();
Thread t = new Thread(r);
t.start();
}


New thread “MyThread” is called and begins the execution and main thread execution is temporarily suspended.

New Thread called “MyThread” runs in a separate stack call as below

Mythread_diag.jpg

JVM keeps on running these 2 threads(Main thread and MyThread) alternatively until both threads complete their execution.

MythreadMainThread_diag.jpg

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on