27-02-25 ----------- Q)Develop a Java application in which, perform the following tasks in parallel. 1)print numbers from 1 to 20 2)print numbers from 21 to 40 class ThreadOne extends Thread{ public void run(){ for(int i=1;i<=20;i++){ System.out.println("Thread 1:"+i); } } } class ThreadTwo extends Thread{ public void run(){ for(int i=21;i<=40;i++){ System.out.println("Thread 2:"+i); } } } class MThreading { public static void main(String[] args) { ThreadOne t1=new ThreadOne(); ThreadTwo t2=new ThreadTwo(); t1.start(); t2.start(); } } Q)What is thread life cycle? =>Creation of a thread,death of the thread and various stages it undergoes between its birth and death put together is nothing but thread life cycle. =>A Java thread has 4 states that describe its life cycle. 1)new state(born state) 2)active state a)runnable state b)running state 3)blocked state 4)dead state DIAGRAM New state:- When the thread object is created the thread is said to be in new state. =>When a thread is new state, body is not attached to it. Note:- run method is the body of the thread. =>When the thread is in new state, it doesn't compete for CPU cycles. Active State:- When start() method is called on the thread object, it transits from new state to active state. =>When a thread is in active state, it competes for CPU cycles as body is attached to it. =>When multiple threads are activated, all are said to be in runnable state. For eg. t1.start(); t2.start(); =>CPU cycles are allocated to which thread at any point in time, it is siad to be in running state. Other active threads in ready queue are said to be in runnable state. =>When a thread is in blocked state, it has body but it doesn't compete for CPU cycles. =>When sleep()/wait() method is called , a thread transits from active state to blocked state. =>When the specified sleeping time is elapsed the thread transits from blocked state to active state again. =>When a thread is blocked by calling wait() method, it comes back to active state only when notify() or notifyAll() method is called. dead state:-A thread transits from active state to dead state when its body is completely executed. =>When a thread is in dead state, it doesn't compete for CPU cycles. Note:- Even though not advisable, a thread can programmatically be killed. I.e. it can be transited from active state to dead state even though its body is not completely executed.