UNIT-3
MULTITHREADING
Multithreading in java:
Multithreading in Java is a programming concept. That allows for the concurrent execution
of multiple parts of a program, known as threads. A thread is similar to a program that has a
single flow of control. It is known as single-threaded programs. The modern operating
systems can execute several programs simultaneously. This ability is known as Multitasking.
In system’s terminology, it is called as Multithreading.
Java.lang.thread:
The java.lang.Thread class in Java represents a thread of execution within a program. It is the
fundamental building block for achieving concurrency in Java applications, allowing multiple
parts of a program to run simultaneously.
Key aspects of java.lang.Thread:
1.concurrency
2.main thread
3.create a thread
4.starting a thread
5.thread life cycle
6.thread methods
The main Thread:
Java program with two threads, one main and three others. The main thread is actually the
main method module, which is designed to create and start the other three threads, namely
T1,T2,T3. Once initiated by the main thread, the threads 1,2,3 run concurrently and share
the resources jointly. Threads in java are subprograms of a main application program and
share the same memory space, they are known as lightweight processes or lightweight
threads.
1
Creation of new threads:
In java you can create a new thread in two far ways.
1. Extending the thread class.
2. Implementing the runnable interface.
Extending the thread class :-
1. Create a new class that extends the thread class.
2. Override the run () method in your new class. The run() method contains the code that
will be executed inside the new thread.
3. Once you’ve defined your custom thread class you can create an instance of it and call the
start() method to being execution.
Here an example of creating a thread by extending the thread class.
Example:
Public class Mythread extends Thread
{
Public void run()
{
System.out.println(“my custom thread is running:”);
}
Public static void main(String [] args)
{
Mythread my thread=new mythread();
Mythread.start();
}
}
Implementing the runnable interface :-
1. Create a new class that implements the runnable interface
2. Implement the run() method in your new class.
3. Create an instance of your custom class and pass if to a new thread object.
2
4. Call the start() method on the thread object. Here an example of creating a thread by
implementing the runnable interface.
Example:
Public class MyRunnable implements Runnable
{
Public void run()
{
System.out.println(“My custom runnable is running:”);
}
Public static void main(String [] args)
{
MyRunnable=new My Runnable();
Thread thread = new Thread (myRunnable);
Thread.start();
}}
Starting a new thread:
To actually create and run an instance of our thread class, we must write the following:
MyThread aThread=new MyThread();
aThread.start();
the first line instantiates a new object of class MyThread. This statement just creates the
object. The thread is in a newborn state.
The second line calls the start() method causing the thread to move into the runnable state.
Then, the java runtime will schedule the thread to run by invoking its run()method. Now the
thread is said to be in the running state.
Life-cycle of a Thread:
During the life time of a thread, there are many states it can enter. They include:
1.Newborn state
2.Runnable state
3.Running state
4.Blocked state
3
5.Dead state
A thread is always in one of these five states. It can move from one state to another via
variety of ways.
1.Newborn State :
When wc create a thread object, the thread is bom and is said lo be in newborn state. The
thread is not yet scheduled for running.
• Schedule it for running using start( ) method.
• Kill it using stop( ) method.
2. Runnable: After the start() method is called on a thread object, it enters the Runnable
state. This doesn’t mean the thread is immediately running. It means it’s eligible to be
executed by the cpu.
3.Running: Once the Operating system’s scheduler allocates cpu time to a runnable thread,
it enters the Running state and begins executing its code(run() method).
4. Blocked: A thread can be temporarily inactive and enter the blocked state if it’s waiting to
acquire a lock. It will remain blocked until the lock is released by another thread.
5.Waiting: A thread enters the waiting state when it’s waiting for another thread to perform
an action. This can happens when a thread calls Wait() on an object, and it will remain in this
state until another thread calls notify() or notifyAll() on the same object.
6. Terminated (Dead): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread methods:
Java's java.lang.Thread class provides a comprehensive set of methods to manage and
control threads. These methods can be broadly categorized based on their functionality:
1. Thread Lifecycle Management:
4
start():
Initiates the execution of the thread by calling its run() method. A new execution path
begins.
run():
Contains the code that the thread will execute. This method is typically overridden when
extending Thread or implementing Runnable.
join():
Causes the current thread to wait until the thread on which join() is called terminates.
sleep(long millis) / sleep(long millis, int nanos):
Pauses the execution of the current thread for a specified duration.
interrupt():
Interrupts this thread. The thread's isInterrupted() status is set to true.
isAlive():
Checks if the thread is currently alive (has been started and not yet terminated).
2. Thread Information and Properties:
currentThread(): Returns a reference to the currently executing thread object.
getId(): Returns the unique identifier of the thread.
getName () / setName(String name): Gets or sets the name of the thread.
getPriority() / setPriority(int newPriority): Gets or sets the priority of the thread.
getState(): Returns the current state of the thread (e.g., NEW, RUNNABLE, BLOCKED,
WAITING, TIMED_WAITING, TERMINATED).
3. Inter-Thread Communication (using Object methods):
wait() / wait(long timeout) / wait(long timeout, int nanos): Causes the current thread
to wait until another thread invokes notify() or notifyAll() for this object, or a
specified timeout elapses. This method must be called within a synchronized block.
notify(): Wakes up a single thread that is waiting on this object's monitor.
notifyAll(): Wakes up all threads that are waiting on this object's monitor.
Thread priority:
In Java, thread priority is a numeric value assigned to a thread that helps the thread
scheduler determine the order in which threads should be executed.
5
Key aspects of thread priority in Java:
Range: Thread priority values range from 1 (minimum) to 10 (maximum).
Constants: The Thread class defines three static final integer constants for common
priority levels:
Thread.MIN_PRIORITY (value 1)
Thread.NORM_PRIORITY (value 5, the default priority for new threads)
Thread.MAX_PRIORITY (value 10)
Methods:
getPriority(): Retrieves the current priority of a thread.
setPriority(int newPriority): Sets the priority of a thread to the
specified newPriority value.
Example program for thread priority:
class A extends Thread
{
public void run()
{
for(int i=1;i<=4;i++)
{
System.out.println("\t From Thread A :i="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=4;j++)
{
System.out.println("\t From Thread B :j="+j);
6
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=4;k++)
{
System.out.println("\t From Thread C :k="+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority
{
public static void main(String[] args)
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("start thread A");
threadA.start();
System.out.println("start thread B");
threadB.start();
7
System.out.println("start thread c");
threadC.start();
System.out.println("End of main thread");
}
}
Multithreading-using isAlive() and join():
In multithreading, the isAlive() and join() methods are used to manage and synchronize the
execution of threads, particularly in languages like Java.
isAlive() Method:
The isAlive() method is used to check the status of a thread.
It returns true if the thread has been started and has not yet terminated (i.e.,
its run() method is still executing or has not yet completed).
It returns false if the thread is in a "new" state (not yet started) or in a "dead" state
(its run() method has finished execution).
This method provides a way to query the current operational status of a thread
without blocking the calling thread.
// Java program to Illustrate isAlive() Method
public class oneThread extends Thread {
public void run()
{
System.out.println("geeks ");
try {
Thread.sleep(300);
}
catch (InterruptedException ie) {
}
System.out.println("forgeeks ");
}
8
public static void main(String[] args)
{
oneThread c1 = new oneThread();
oneThread c2 = new oneThread();
c1.start();
c2.start();
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
}
}
join() Method:
The join() method is used to ensure that a calling thread waits for the completion of
another specified thread.
When thread_A.join() is called from thread_B, thread_B will pause its execution and
wait until thread_A has finished its run() method and terminated.
This method is crucial for ensuring proper sequencing of operations where one
thread's work depends on the completion of another thread's work.
join() can also be called with a timeout argument, allowing the calling thread to wait
for a specified duration before proceeding, even if the target thread has not yet
terminated.
Example program:
Public class JoinTest extends Thread
{
Public void run()
{
For(int i=1;i<=3;i++)
{
Try
{
Thread.sleep(1000);
}
9
Catch(Exception e)
{
System.out.println(e);
}
System.out.println(“Tutorialspoint”+i);
}
}
Public static void main(String args[])
{
JoinTest t1=new JoinTest();
JoinTest t2=new JoinTest();
JoinTest t3=new JoinTest();
T1.start();
Try
{
T1.join();
}
Catch(Exception e)
{
System.out.println(e);
}
t2.start();
T3.start();
}
}
Synchronization:
In multithreading, synchronization is important to make sure multiple threads safely work on
shared resources. Without synchronization, data can become inconsistent or corrupted if
multiple threads access and modify shared variables at the same time. In Java, it is a
mechanism that ensures that only one thread can access a resource at any given time. This
10
process helps prevent issues such as data inconsistency and race conditions when multiple
threads interact with shared resources.
General Form of Synchronized Block
synchronized(sync_object)
{
// Access shared variables and other
shared resources
}
Types of Synchronization
There are two type of synchronizations in Java which are listed below:
Process Synchronization
Thread Synchronization
Example program:
// Java Program to demonstrate synchronization in Java
class Counter {
private int c = 0; // Shared variable
public synchronized void inc() {
c++;
}
public synchronized int get() {
return c;
}
}
public class Geeks {
public static void main(String[] args) {
Counter cnt = new Counter(); // Shared resource
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
cnt.inc();
}
});
11
Thread t2 = new Thread(() ->
{
for (int i = 0; i < 1000; i++)
{
cnt.inc();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + cnt.get());
}
}
Communication between threads(Interthread communication):
Inter-thread communication in Java refers to the mechanisms that allow multiple threads
within the same process to coordinate their actions and share data efficiently and
safely. Since threads share the same memory space, inter-thread communication is crucial
for managing access to shared resources and ensuring proper synchronization.
Key methods and concepts for inter-thread communication in Java:
wait(), notify(), and notifyAll() methods:
These methods are provided by the Object class and are fundamental for
thread coordination.
wait(): Causes the current thread to release the lock on an object and enter a
waiting state until another thread invokes notify() or notifyAll() on the same
object. This prevents "busy waiting" and conserves CPU cycles.
12
notify(): Wakes up a single thread that is waiting on the object's monitor
(lock). The choice of which thread to wake up is determined by the JVM's
thread scheduler.
notifyAll(): Wakes up all threads that are waiting on the object's monitor. This
is often preferred to ensure no threads are left waiting indefinitely, especially
when multiple threads might be waiting for the same condition.
Important Note: These methods must be called within a synchronized block
or method, as they rely on the object's monitor.
Synchronization (synchronized keyword):
The synchronized keyword is used to control access to shared resources by
allowing only one thread at a time to execute a specific block of code or
method.
It prevents race conditions and data inconsistency when multiple threads try
to modify shared data concurrently.
Synchronization ensures that the wait(), notify(), and notifyAll() methods
operate correctly by providing a mechanism for acquiring and releasing object
monitors.
join() method:
The join() method of the Thread class allows one thread to wait for another
thread to complete its execution before proceeding.
If t is a Thread object, calling t.join() in another thread will cause that thread
to pause until t finishes executing.
interrupt() method:
The interrupt() method of the Thread class is used to signal a thread that it
should stop its current activity, particularly if it's in a waiting or sleeping state
(e.g., during Thread.sleep() or Object.wait()).
It sets the interrupted status of the thread, which can then be checked by the
thread to handle the interruption gracefully.
Purpose of Inter-thread Communication:
Coordination: Enables threads to coordinate their actions, ensuring that tasks are
performed in a specific order or when certain conditions are met.
Resource Management: Facilitates safe and efficient sharing of resources among
multiple threads, preventing data corruption and inconsistencies.
Improved Performance: Avoids busy waiting and allows threads to efficiently utilize
CPU resources by waiting only when necessary.
13
Preventing Deadlocks and Race Conditions: Proper use of synchronization and inter-
thread communication mechanisms helps in avoiding common concurrency issues
like deadlocks and race conditions.
Input/Output: reading and writing data:
Reading input with java.utill.Scanner class
We can use Scanner class java.utill package to read input from the keyboard or a text file.
When the Scanner class receives input, it breaks it into several pieces, called tokens.
These tokens can be retrieved from the Scanner object using the following methods:
next() - to read a string
nextline() - to read a string till the end of the line
next().charAt(0) - to read a single char
nextByte() - to read byte value
nextInt - to read an interger value
nextFlaot() - to read float value
nextLong() - to read long value
nextDouble() -to read double value
To read input from keyboard ,we can use Scanner class as:
scanner sc = new Scanner (System.in);
Program:
//Scanner to scan the input from keyboard
Import java.utill.Scanner:
Class ex3
{
Public static void main (String args[])
{
System.out.print(“enter id name sal:”);
Scanner sc =new scanner (System.in);
int id =sc.nextInt();
string name=sc.next();
float sal=sc.nextFloat();
System.out.println(“Id=”+id);
System.out.println(“Name=”+name);
14
System.out.println(“Sal=”+sal);
}}
Output: Enter id name sal:10 gopal 8900
Displaying output with System.out.printf()
To formate and display the output, printf() method is available in PrintStream class. This
method works similar to printf() function in c . we know that System.out returns PrintStream
class object, so to call the printf()method , we can use:System.out.printf().
The following format characters can be used in printf():
%s - string
%c – char
%d- decimal integer
%f - float number
%o - octal number
%b,%B - boolean value
%x,%X - hexadecimal number
%n - new line
An example for using printf() is given below: System.out.printf(“salary=%f”,sal);
Program:
//printf() in java
class ex1
{
public static void main(String args[])
{
String s1=”hello”;
Int n =65; float f = 15.123;
System.out.printf(“String=%s%nnum=%d%nhexadecimal=%x%nfloat=%f”,s1,n.n,f);
}}
Output: String=hello
Num =65
Hexadecimal=41
15
float=15.123
JAVA.IO.PACKAGES:
A package represents a directory that contains related group of classes and interfaces.
For example when we write statements like:
Import java.io.*;
We are importing classes of java.io package. Here, java is a directory name and io is another
sub directory within it. And the ‘*’ represents all the classes and interfaces of that io sub
directory.
java.io: io stands for input and output. This packages contains streams. A stream represents
flow of data from one place to another place. Streams are useful to store data in the form of
files and also to perform input-output related tasks.
The java.io package in Java provides a comprehensive set of classes for performing input
and output (I/O) operations. This package is fundamental for handling data streams, file
system interactions, and object serialization.
Key functionalities and components of java.io:
Streams:
The core concept of java.io revolves around streams, which represent a sequence of data
flowing from a source to a destination.
Input Streams: Classes like Input Stream and Reader are used for reading
data from various sources (e.g., files, network connections, memory).
Output Streams: Classes like Output Stream and Writer are used for writing
data to various destinations (e.g., files, network connections, console).
Byte Streams vs. Character Streams:
Byte Streams: Handle raw binary data
(e.g., FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutp
utStream).
Character Streams: Handle character data, automatically handling character
encoding (e.g., File Reader, File Writer, Buffered Reader, Print Writer).
File Operations:
Provides classes for interacting with the file system, such as creating, deleting, reading, and
writing files (e.g., File, Random Access File).
Object Serialization:
Enables the conversion of objects into a byte stream for storage or transmission, and vice
versa (e.g., Object Input Stream, Object Output Stream).
16
Buffering:
Offers buffered stream classes
(e.g., BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream) to
improve I/O performance by reducing the number of direct interactions with the underlying
system.
Other Utilities:
Includes classes for specialized I/O needs, such as Data Input Stream and Data Output
Stream for reading/writing primitive data types, and Piped Input Stream/Piped Output
Stream for inter-thread communication.
In essence, the java.io package is the backbone for any Java application requiring interaction
with external data sources or destinations.
APPLET PROGRAMMING
Applet:
1. An applet is a java program written in the java programing language that can be included
in an html page.
2. An applet is a java program that can be embedded into a web page.it run’s inside the web
browser and works at client side.
3. An applet is embedded in an html page using the applet or object tag and hosted on a
web server.
4. Applet are used to make the website more dynamic and entertaining.
5. It is not a standalone program and it doesn’t contain main () method.
6. Html page that contains class file called an applet.
Whenever we write an applet program we need to write two programs separately:
1. Java applet program
2. Html program
Note:- 1. Applet do not need a main method.
2. Applet must be run under an applet view or a java compiled browser.
3. Applet=html + java class code.
Example:-
Import java.applet.*;
Import java.awt.*;
17
Public class hello world extends applet {
Public void paint(Graphics g)
{
g.drawString(“hello world”,20,20)
}}
We have created a basic java applet name ‘Hello World’. This applet displays the text ‘Hello
World’ at the coordinates (20,20) on the screen. The paint method is a built-in function in
the applet class that allows us to draw strings, lines, shapes and more.
Embedding java applet in a webpage :-
Once your applet is ready, it’s time to embed it into a webpage. This is done using the “tag
in your HTML code.
HTML code :-
<html>
<applet code=”hello world.class”width=”300”height=”200”>
</applet>
</html>
This will display your java applet within a 300x200 pixel area on your webpage.
Hierarchy of applet:-
Hierarchy of applet before landing up on stages in the lifecycle of the java applet that is as
follows in the below media:
Applet life cycle :-
The applet life cycle in java can be defined as the process of how an applet object is created,
started, stopped, and destroyed during the entire execution of the applet.
18
There are mainly five methods used in the applet life cycle:
1. Init () means initialization
2. Start ()
3. Paint ()
4. Stop ()
5. Destroy ()
Method 1: initialization
1. This is the first method to be called variables can be initialized here 2. This method can be
called only once during the run time of the applet
3. It is invoked at the time of initialization
Syntax:-
Public void init()
{
to initialize objects
}
Method 2: start ()
1. This method is called after init () method.
2. Start () method is used for starting the applet
3. It is also called to restart an applet it has been stopped. i.e. to resume the applet
Syntax:- Public void start ()
{
19
// to start the applet code
}
Method 3: paint ()
1. Paint () method is used for painting any shapes like square, rectangle, trapeziums, etc.
2. Paint () method has one parameter of type graphics class, this graphics class enables the
painting features in an applet
Syntax:-
Public void paint (Graphics g)
{
// any shape’s code
}
Method 4: stop ()
1. After stop () method called, we can also use start () method whenever we want.
2. This method mainly deals with clean up code.
3. It is invoked every time the browser is stopped, minimized or when there is an abrupt
failure in the application.
Syntax:
Public void stop ()
{
//to stop the applet code
}
Method 5: destroy ()
1. Destroy () method is used to destroy the application once we are done with our applet
work. It can be invoked only once.
2. Once applet is destroyed we can’t start () the applet (we cannot restore the applet again)
3. 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
}
20
Example:
Import java.applet.Applet;
Import java.awt.Graphics;
Public class LifeCycleApplet extends Applet
{
Public void init ()
{
System.out.println(“Applet initialization”);
}
Public void start ()
{
System.out.println(“Applet started”);
}
Public void stop ()
{
System.out.println(“Applet stopped”);
}
Public void destroy ()
21
{
System.out.println(“Applet destroyed”);
}
Public void paint(Graphics g)
{
g.drawString(“Hello, Applet life cycle “,20,20);
}}
To use this applet you need to embed it in an HTML file as follows. HTML CODE:
<html>
<head>
<title> applet Life Cycle Example </title>
</head>
<body>
<h1>Applet Life Cycle Example</h1>
<applet code=”LifeCycleApplet.class” width=”300” height=”200”> Your browser does not
support java applets.
</applet>
</body>
</html>
Applet update () and repaint ();
Repaint () : the repaint () is intended to allow various methods to call for a re-rendering of
the component. No graphics context is needed for repaint ().
Update (): update is called when the window is re-sized. The default implementation of
update (): first clears the background; then calls paint ().
Example:
Import java.applet.Applet;
Import java.awt.color;
Import java.awt.Graphics;
Public class RepaintUpdateApplet extends Applet
22
{
Private string message = “Initial Message”;
Private int counter = 0;
Public void init ()
{
setBackground(color.white);
setForeground(color.blue);
System.out.println(“Applet initialization”);
}
Public void start ()
{
System.out.println(“Applet started”);
} Public void stop ()
{
System.out.println(“Applet stopped”);
} Public void destroy ()
{
System.out.println(“Applet destroyed”);
} Public void update(Graphics g)
{
System.out.println(“update () called.”);
g.clearRect(0, 0, getwidth(),getHeight());
paint(g);
}
Public void paint(Graphics g)
{
System.out.printl(“paint () called.”);
g.drawString(message, 20, 20);
}
23
Public void changeMessage()
{
Counter++;
message = “message changed ” + counter + “times”;
repaint();
}
}
To use this applet you need to embed it in an HTML file as follows. Html code:
<!Doctype html>
<html>
<head>
<title>Repaint and Update Applet Example</title>
</head>
<body>
<h1>Repaint and Update Applet Example</h1>
<applet code=”RepaintUpdateApplet.class” width=”300” height=”200”> Your browser does
not support java applets.
</applet>
<script>
Function changeAppletmessage()
{
Var applet=document.applets[0];
Applet.changemessage();
}
</script>
<button onclick=”changeAppletMessage()”>change Message</button>
</body>
</html>
24
Java Applet Class :
For Creating any applet in Java, we use the java.applet.Applet class. It has four Methods in
its Life Cycle of Java Applet. The applet can be executed using the applet viewer utility
provided by JDK. A Java Applet was created using the Applet class, i.e., part of the
java.applet package.
The Applet class provides a standard interface between applets and their environment. The
Applet class is the superclass of an applet that is embedded in a Web page or viewed by the
Java Applet Viewer. The Java applet class gives several useful methods to give you complete
control over the running of an Applet. Like initializing and destroying an applet, It also
provides ways that load and display Web Colourful images and methods that load and play
audio and Videos Clips and Cinematic Videos.
In Java, there are two types of Applet
1. Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its
Applet class
2. Java Applets is based on the Swing package by extending its Applet Class in it.
Life Cycle of Java Applet Class:
Life Cycle Of java Applet Class has four main methods :
1. init()
2. Start()
3. Stop()
4. Destroy()
Explanation:
1. Void init(): This init()method is the first method of a java applet. This is used to initialize
the applet when the applet begins to execute 2. Void start(): void start()this method is called
25
automatically after the init() method, and it is used to start the Applet and to
implementation of an applet.
3. Void stop(): void stop()is used to stop the Applet or to stop the running applet
4. Void destroy(): void destroy() is used to destroy the Applet / to Terminate the applet.
Other Methods in AppletClass:
5. System.out.println(String): This Method Works from appletviewer, as not from
browsers, and it Automatically opens an Output window. 6. ShowStatus(String): This Method
Displays the String in the Applet’s status line, and each call overwrites the previous call, and
You have to allow time to read the line.
7. String getParameter(String ParameterName): It Returns
the value of a parameter defined in a Current Applet.
8. Image getImage(URLurl): This method returns an Image object which contains an image
specified at its location, url.
9. Voidplay(URLurl): This method can play an audio clip found at the specified location, url.
10. setStub: It sets this applet’s stub, which is done automatically by the system.
11. isActive: This method Determines if this current applet is active. Then Applet is marked
active just before its start method is invoked. Then It becomes inactive immediately after its
stop method when it is initialized.
Applet structure:
Import java.applet.Applet;
Import java.awt.Graphics;
Public class MyApplet extends Applet {
// Initialization method
Public void init() {
// Initialization code
}
// Start method
Public void start() {
// Code to start/restart the applet
}
// Stop method
Public void stop() {
26
// Code to stop the applet }
// Destroy method Public void destroy()
{
// Cleanup code
}
// Paint method Public
void paint(Graphics g)
{
g.drawString(“Hello, Applet!”, 20,20);
}}
Explanation:
Import Statements: The applet requires classes from the java.applet and java.awt packages.
Init() Method: Used for initialization code that you want to run once, such as setting up the
user interface.
Start() Method: Contains code that should run when the applet starts or restarts.
Stop() Method: Contains code to pause or stop the applet’s execution.
Destroy() Method: Called when the applet is destroyed to perform any cleanup.
Paint(Graphics g) Method: Used for rendering the applet’s content on the screen
27