Threading:
A process can contain one or more threads.
In java by default two threads will run i.e. main() & garbage collection. we can create as many as threads as possible we want.
Benefit of threads:
We can delegate a long running tasks which does not require any i/p from user to a thread resulting in fast execution of main thread(concentrated logic).
Steps to create thread:
Method 1:
- Create a class which extends “Thread”
- Override “run()”.
- Create a object of a class which extends thread by using below line of code.
Thread obj=new <class which extends thread>;
4. Call method “start()”, internally it will call method “run()”.
Lifecycle of Thread:
Thread is a light weight process.
1. New State:
After the creation of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
2. Runnable State:
A thread start its life from Runnable State. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the process.
3. Running State:-
A thread is running state that means the thread is currently executing. There are several ways to enter in runnable state but there is only one way to enter in running state, the scheduler select a thread from runnable part.
4. Dead State:-
A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
5. Blocked:-
A thread can enter in this state because of waiting the resources that are hold by another thread.
class temp extends Thread { public void run() { System.out.println("In run method"); } } class TestThread { public static void main(String args[]) { Thread obj=new temp(); Obj.start(); } }
Q. What is the difference between calling method start() & calling method run() of thread?
i. start method of thread will internally create a new thread & calls run method. The sequence of execution of thread in unpredictable.
ii. run method will be called as a normal method in a main thread,if call externally.
class Temp extends <strong>Thread</strong> { public void run() { for(int i=0;i<20;i++) { System.oput.println("In Run Method"); } } } class TestThread { public static void main(String args[]) { Thread obj=new Temp(); Obj.start(); for(int i=0;i<20;i++) { System.out.println("In Main Method"); } } }
O/P:-
In Main Method // will run fifteen times.
In Run Method // will run twenty times.
In Main Method // will run five times.
Leave a Reply to ShraddhaCancel reply