0% found this document useful (0 votes)
21 views8 pages

Lifecycle and States of A Thread in Java

Java notes

Uploaded by

sarveshsawant269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views8 pages

Lifecycle and States of A Thread in Java

Java notes

Uploaded by

sarveshsawant269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Lifecycle and States of a Thread in Java

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one
of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.

Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code is
yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each
and every thread runs for a short while and then pauses and relinquishes the CPU to another
thread so that other threads can get a chance to run. When this happens, all such threads
that are ready to run, waiting for the CPU and the currently running thread lie in a runnable
state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently
the lock is acquired by the other thread. The thread will move from the blocked state to
runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join()
method. It will move to the runnable state when other thread will notify or that thread will
be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

 Because it exits normally. This happens when the code of the thread has been
entirely executed by the program.
 Because there occurred some unusual erroneous event, like a segmentation fault or
an unhandled exception.
Implementing the Thread States in Java
In Java, to get the current state of the thread, use Thread.getState() method to get the current state
of the thread. Java provides java.lang.Thread.State class that defines the ENUM constants for the
state of a thread, as a summary of which is given below:
1. New
Thread state for a thread that has not yet started.
public static final Thread.State NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the operating system such as a processor.
public static final Thread.State RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting
for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method
after calling Object.wait().
public static final Thread.State BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:
 Object.wait with no timeout
 Thread.join with no timeout
 LockSupport.park
public static final Thread.State WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state
due to calling one of the following methods with a specified positive waiting time:
 Thread.sleep
 Object.wait with timeout
 Thread.join with timeout
 LockSupport.parkNanos
 LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
Declaration: public static final Thread.State TERMINATED

Life Cycle of Java Applet


An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works on the client-side. An applet is embedded in an HTML page using the APPLET or OBJECT
tag and hosted on a web server. The entire life cycle of an applet is managed by the Applet Container.
All applets are sub-classes (either directly or indirectly) of java.applet.Applet class. Applets are not
stand-alone programs. They run either within a web browser or an applet viewer.

Note:
Java applet is deprecated because it’s no longer widely used on the web. The popularity of applets
has decreased over the years as browser support for applets has declined, and more advanced
technologies such as web-based applications and JavaScript have become more prevalent.
Additionally, applets are considered a security risk as they can execute arbitrary code on the client
machine, and many browsers now disable them by default. As a result, Java’s applet technology is
no longer seen as a valuable feature for Java developers and is removed from the newer versions of
Java.

 Applets generate Dynamic content

 Applets work on the client-side

 The response time is fast


We can view our Applet with the help of a standard applet viewer tool called Applet Viewer. Unlike
the general executions and outputs of the java programs, applet execution does not begin at main()
method, and the output of an applet window is not catered by System.out.println(). Rather it is
handled with various Abstract Window Toolkit (AWT) methods, such as drawString().

Let us do see a hierarchy of Applet before landing up on stages in the lifecycle of the java applet that
is as follows in the below media:

Stages in the Life Cycle of Java Applet

 Initializing an Applet

 Starting the Applet

 Painting the Applet

 Stopping the Applet

 Destroying the Applet

In order to implement the Applet we need to import awt package,

java.awt.applet.*;

Life Cycle of Applet

Step 1: Initialization

public void init()

There is no main method unlike our normal java programs. Every Applet will start it’s execution from
init() method. It is executed only once

Step 2: Start
public void start()

After init() method start() method is invoked. Executed when the browser is maximized

Step 3: Paint

public void paint (Graphics g)

Paint method is used to display the content on the applet. We can create the objects or components
to the applet or we can directly write a message on the applet. It will take Graphics class as a
parameter.

Step 4: Stop

public void stop()

stop() method is used to stop the applet. It is executed when the browser is minimized.

Step 5: Destroy

public void destroy()

destroy() method is used to completely close the applet. It is executed when the applet is closed.

Implementation:

Implementation of java Applet can be done in two ways as follows:

1. Using HTML file

2. Applet viewer tool

Way 1: Using HTML file

<HTML>
<applet>
code,width,height
</applet>
</HTML>

Note: Drawbacks of using HTML file is you need a plugin (java plugin) to run it on your browser.

Way 2: Applet viewer tool

Methods of Applet Life Cycle:

There are five methods of an Applet Life Cycle namely;

1. init()

2. start()

3. paint()

4. stop()

5. destroy()
All these are available in AWT Package java.awt.applet.* and in order ton import paint (Graphics g)
we do use java.awt.component package

Let’s understand each method in a detailed manner :

Method 1: init()

 This is the first method to be called

 Variables can be initialized here

 This method can be called only once during the run time of the applet

 It is invoked at the time of Initialization

Syntax:

public void init()

// To initialize objects

Method 2: start()

 This method is called after init() method

 start() method is used for starting the applet

 It is also called to restart an applet after it has been stopped. i.e. to resume the applet

Syntax:

public void start()

// To start the applet code

Note: init() is called once i.e. when the first time an applet is loaded whereas start( ) is called each
time an applet’s HTML document is displayed onscreen.

Method 3: paint()

void paint(Graphics g){ }

 paint() method is used for painting any shapes like square, rectangle, trapeziums, etc.

 paint() method has one parameter of type Graphics Class, this Graphics class enables the
painting features in an applet.

 This parameter will contain the graphics context, which is used whenever output for the
applet is required.
Syntax:

public void paint(Graphics graphics)

// Any shape's code

Note: This is the only method among all the method mention above, which is parameterized.

Method 4: stop()

 It is invoked every time the browser is stopped, minimized or when there is an abrupt failure
in the application.

 After stop()method called, we can also use start() method whenever we want.

 This method mainly deals with clean up code.

 The stop( ) method is called when a web browser leaves the HTML document containing the
applet when it goes to another page, for example, when stop( ) is called, the applet is
probably running. You should use stop( ) to suspend threads that don’t need to run when the
applet is not visible. You can restart them when start( ) is called if the user returns to the
page.

Syntax:

public void stop()

// To stop the applet code

Method 5: destroy()

 destroy() method is used to destroy the application once we are done with our applet work.
It can be invoked only once.

 Once applet is destroyed we can’t start() the applet (we cannot restore the applet again)

 The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory.

Syntax:

public void destroy()

// To destroy the applet

Note: The stop( ) method is always called before destroy( )


Syntax: Entire Applet Life Cycle
Code for copy from one file to other

import java.io.*;
import java.util.*;

public class FileCopy {


public static void copy(File source, File destination) throws IOException {
try (FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(destination)) {
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
}
System.out.println("File Copied");
}

public static void main(String[] args) throws IOException {


Scanner sc = new Scanner(System.in);
System.out.println("Enter source file:");
File source = new File(sc.nextLine());
System.out.println("Enter destination file:");
File destination = new File(sc.nextLine());
copy(source, destination);
}
}

You might also like