Skip to main content

Life Cycle of a Thread


Thread life cycle is divided into five stages/states:
1.      New born
2.      Runnable
3.      Running
4.      Blocked
5.      Dead
New Born
When user creates object of thread by using thread class or by using runnable interface, then the thread is said to be in new born stage. Note that, the thread is not currently executing.


If user provides start() method to the new born thread, then it will go to the running or runnable stage. If user provides stop() method to the new born thread, then it will go to the dead stage.
Running Stage
Running means a processor has given time to the thread for execution. The thread will run until it relinquishes (leaves) by its own or it is preempted by the higher priority thread. This can be done by following three situations:
·         If the thread is suspended by using suspend() method then it will quit the control. The suspended thread can come back for execution by using resume() method.




·         If the thread is put to sleep for a specified time period then the running process will relinquish the control. This can be done by using sleep (time) method. Here user has to specify the time in milliseconds.






Example:

for (int i = 1; i < = 1000; i++)
{
            If (i == 700)
            sleep(1000)                 // 1000 ms = 1 sec
}

Here, we have taken one loop which will print numeric integers from 1 to 1000 constantly. But, when the variable i will reach to 700, sleep() method will send this thread to sleep for 1 second. And after completing the sleeping time, the thread will get resumed by processor and start printing from 701 to 1000.

·         If the thread is hold for any event to occur, then the thread will relinquish the control. Such type of threads can be rescheduled by using notify() method.





Runnable
Here, the thread is ready to run and it is waiting for execution. If multiple threads are having same priority then, they can be executed by Round Robin manner. Processor can apply any algorithm SJF (Shortest Job First), FCFS (First Come First Served) for the thread execution. The thread will relinquish the control at the end and it will join the queue for the execution.
Blocked
A thread is said to be in block state, if it is prevented from entering into running or runnable state. A thread can be blocked when it is suspended or sleeping or waiting for any event.
Dead
A thread is in dead state, if either it has completed successful execution or it is forced by using stop() from any other state.

Classroom Q & A

Q: How many threads can a process have?
A: As many threads as it can handle in its memory space. I have seen applications with thousands of threads. Of course, these applications were running on large servers with lots of memory and multiple CPUs.

Q: And all of these threads are running at the same time?
A: Well, yes and no. To be more precise, a process can have multiple threads that are runnable at the same time. However, the number of threads actually running at any given time is dependent on the number of CPUs (processors) available.

Q: So how many threads can run on a CPU at one time?
A: Just one! That means your typical desktop computer with its one CPU can execute only one thread at a time.

Q: Then what are the other threads doing?
A: They are still runnable, but they are waiting in a queue for the thread scheduler (which is really the JVM) to schedule CPU time for them. For example, suppose that you have two processes and each process has two threads. If one CPU is available, then only one of those threads can be executing at a time, and the other three are waiting.

Q: How long do they wait?
A: Well, to be precise, it depends. The amount of time a thread gets on the CPU depends on an indeterminate number of factors. Some platforms (such as Windows 95/NT/XP) use time-slicing, meaning that a thread gets a certain amount of CPU time, and that’s it. Other platforms do not time-slice, but instead schedule threads based on their priority. The thread scheduler for the JVM uses fixed priority scheduling. This term means that threads are scheduled based on their priority, with higher-priority threads running before lower-priority threads. The JVM thread scheduler is also preemptive, which means that if a higher-priority thread comes along, it preempts any currently running lower-priority thread.

Q: So I can create a Java thread, give it a high priority, and it will hogthe CPU until it is finished?
A: Perhaps, but doubtful. Many operating systems take certain measures to ensure that threads do not hog the CPU, like intentionally scheduling a lower-priority thread over a higher one. Therefore, you should never rely on thread priority as part of your algorithm logic. If you need one thread to finish before another, do not assume that this can be accomplished by using priorities. The purpose of thread priorities is only to allow you to denote one task as more important than another.

Q: Why use threads at all if you do not have control over which one is running?
A: Well, that’s a good question. A good rule of thumb is to not use multithreading if you can solve the problem at hand without it. However, in many real-world programming situations, they can’t be avoided. In fact, threads can often make a problem easier to solve, while improving the performance of the application at the same time. Therefore, it is important to understand not just how to write a thread, but how the thread behaves after it starts running.


Notes From: Prof. Pooja Joshi

Compiled By: Chaudhary Amit V.

Comments

Popular posts from this blog

Characteristics of a Good Programming Language

Till now there are many high level languages which are very popular, and there are others, which could not become so popular in-spite of being very powerful. There might be many reasons for the success of a language, but one obvious reason is the characteristics of the language. Several characteristics believed to be important with respect to making a programming language good are briefly discussed below. Simplicity A good programming language must be simple and easy to learn and use. For example, BASIC is liked by many programmers only because of its simplicity. Thus, a good programming language should provide a programmer with a clear, simple and unified set of concepts which can be easily grasped. It is also easy to develop and implement a compiler or an interpreter for a programming language that is simple. However, the power needed for the language should not be sacrificed for simplicity. The overall simplicity of a programming language strongly affects the readability of the pr...

Angular 4 and Firebase Authentication: Email/Password

In our  previous  article we saw how to create authentication module using Google identity provider. Now we will see how to implement Email and Password authentication using Firebase. We will use Bootstrap form to create intuitive user interface for sign-up and login using Email and Password. Step 1: Create signUp component. ng generate component signUp Step 2: Create custom form in sign-up.component.html file. The result of above code: Step 3: Add two functions for creating the user and login using Email and Password in src/app/providers/AFAuth.ts file. Step 4: Call createUserWithEmailAndPassword function in service from sign-up.component.ts. Step 5: Update routing configuration in app.module.ts  to include signUp component. Step 6: Update Login form to have Bootstrap form. The result of the above code. Step 7: Enable Email/Password component in Firebas...

Angular 4 and Firebase Authentication: Setup

If you have come to this article, it means you are keen to learn new technology and that too Firebase. I love Firebase because it provides all basic but important features of any web application. Take for example, authentication, which is cumbersome and risky if not implemented with utmost care. And when we have the integration of Angular and Firebase, it becomes a lot easier for a developer to build such crucial modules in less time with minimal efforts. In this article we will create a simple Angular application using Firebase. I am going ahead with the understanding that you know the benefits of Firebase and have little knowledge about it. There are plenty of posts out on the web if you are behind. Step 1: Install Angular CLI (if not installed). npm install -g angular-cli Step 2: Create new Angular 4 project. By default now angular CLI will create Angular 4 project so you need not fret. ng new firebase-authentication Step 3: Check whether the ne...