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
- 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
- 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.
- Public static void main(String[] args){
- ...............
- }
Public static void main(String[] args){ ............... }
main thread starts a new thread as below
- Public static void main(String[] args){
- Runnable r = new MyThread();
- Thread t = new Thread(r);
- t.start();
- }
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
JVM keeps on running these 2 threads(Main thread and MyThread) alternatively until both threads complete their execution.
Your concepts are very clear and good, Thanks for all the effort you have made to put this stuff on the site.