java.lang.Thread
class.run()
method available in the Thread class.run()
method.start()
method to start the execution of a thread. start()
invokes the run()
method on the Thread object.// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run() {
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId() +
" is running");
} catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
java.lang.Runnable
interface and override run()
method.start()
method on this object.// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run() {
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId() +
" is running");
} catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
yield()
, interrupt()
etc. that are not available in Runnable interface.
currentThread()
which is present in Thread class.// Java program to control the Main Thread
// Importing required classes
import java.io.*;
import java.util.*;
// Class 1
// Main class extending thread class
public class Test extends Thread {
// Main driver method
public static void main(String[] args) {
// Getting reference to Main thread
Thread t = Thread.currentThread();
// Getting name of Main thread
System.out.println("Current thread: " + t.getName());
// Changing the name of Main thread
t.setName("Geeks");
System.out.println("After name change: " + t.getName());
// Getting priority of Main thread
System.out.println("Main thread priority: " + t.getPriority());
// Setting priority of Main thread to MAX(10)
t.setPriority(MAX_PRIORITY);
// Print and display the main thread priority
System.out.println("Main thread new priority: " + t.getPriority());
for (int i = 0; i < 5; i++) {
System.out.println("Main thread");
}
// Main thread creating a child thread
Thread ct = new Thread() {
// run() method of a thread
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Child thread");
}
}
};
// Getting priority of child thread
// which will be inherited from Main thread
// as it is created by Main thread
System.out.println("Child thread priority: " + ct.getPriority());
// Setting priority of Main thread to MIN(1)
ct.setPriority(MIN_PRIORITY);
System.out.println("Child thread new priority: " + ct.getPriority());
// Starting child thread
ct.start();
}
}
// Class 2
// Helper class extending Thread class
// Child Thread class
class ChildThread extends Thread {
@Override public void run() {
for (int i = 0; i < 5; i++) {
// Print statement whenever child thread is
// called
System.out.println("Child thread");
}
}
}
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
public void run()
: is used to perform action for a thread.public void start()
: starts the execution of the thread.JVM calls the run() method on the thread.public void sleep(long miliseconds)
: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.public void join()
: waits for a thread to die.public void join(long miliseconds)
: waits for a thread to die for the specified miliseconds.public int getPriority()
: returns the priority of the thread.public int setPriority(int priority)
: changes the priority of the thread.public String getName()
: returns the name of the thread.public void setName(String name)
: changes the name of the thread.public Thread currentThread()
: returns the reference of currently executing thread.public int getId()
: returns the id of the thread.public Thread.State getState()
: returns the state of the thread.public boolean isAlive()
: tests if the thread is alive.public void yield()
: causes the currently executing thread object to temporarily pause and allow other threads to execute.public void suspend()
: is used to suspend the thread(depricated).public void resume()
: is used to resume the suspended thread(depricated).public void stop()
: is used to stop the thread(depricated).public boolean isDaemon()
: tests if the thread is a daemon thread.public void setDaemon(boolean b)
: marks the thread as daemon or user thread.public void interrupt()
: interrupts the thread.public boolean isInterrupted()
: tests if the thread has been interrupted.public static boolean interrupted()
: tests if the current thread has been interrupted.class MyThread extends Thread {
public void run() {
// Code to be executed by the thread
System.out.println("Thread running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
System.out.println("Runnable running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the thread
}
}
Threads in Java can be in different states:
IllegalThreadStateException
will be thrown./* Thread 1 */
class Thread1 extends Thread {
public void run() {
System.out.println("Thread 1");
System.out.println("i in Thread 1 ");
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 1 Completed.");
}
}
/* Thread 2 */
class Thread2 extends Thread {
public void run() {
System.out.println("Thread 2");
System.out.println("i in Thread 2 ");
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
System.out.println("Thread 2 Completed.");
}
}
/* Driver code */
public class ThreadDemo {
public static void main(String[] args) {
// life cycle of Thread
// Thread's New State
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
// Both the above threads are in runnable state
// Running state of Thread1 and Thread2
t1.start();
// Move control to another thread
t2.yield();
// Blocked State Thread1
try {
t1.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
System.out.println("Main Thread End");
}
}
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
// HelloWorld class extends Applet
public class HelloWorld extends Applet {
// Overriding paint() method
@Override
public void paint(Graphics g) {
g.drawString("Hello World", 20, 20);
}
}
java.applet.Applet class:
public void init()
: is used to initialized the Applet. It is invoked only once.public void start()
: is invoked after the init()
method or browser is maximized. It is used to start the Applet.public void stop()
: is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.public void destroy()
: is used to destroy the Applet. It is invoked only onceimport java.applet.Applet;
: This imports the Applet class from the java.applet
package, which is necessary for creating applets.import java.awt.Graphics;
: This imports the Graphics class from the java.awt
package, which provides methods for drawing shapes and text.public class BasicApplet extends Applet
: Defines a subclass named BasicApplet
that extends the Applet class. This means BasicApplet
inherits all methods and properties of the Applet class.init()
: This method is called when the applet is first loaded into memory. It is typically used for initialization tasks such as setting up variables, loading resources, etc.start()
: This method is called when the applet is started, either after initialization or when the user revisits the applet. It can be used to start animations or other ongoing processes.paint(Graphics g)
: This method is called whenever the applet needs to be redrawn, such as when it is first displayed or when it is uncovered after being hidden by another window. It is where you define the graphical content of the applet using the Graphics object g.stop()
: This method is called when the applet is stopped, such as when the user navigates away from the webpage containing the applet. It can be used to pause animations or other ongoing processes.destroy()
: This method is called when the applet is destroyed, such as when the browser is closed or the webpage is refreshed. It can be used to release resources or perform clean-up tasks.paint(Graphics g)
method, you use methods of the Graphics object g to draw shapes, text, images, etc. In the example provided (g.drawString("Hello, World!", 20, 20);)
, it draws the text "Hello, World!" at coordinates (20, 20) on the applet.java.awt.Component class
public void paint(Graphics g)
: is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc
java.applet.
Applet class 4 life cycle methods and java.awt.Component
class provides 1 life cycle methods for an applet.Simple example of Applet by html file:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet {
public void paint(Graphics g) {
g.drawString("welcome", 150, 150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300"> </applet>
</body>
</html>
Simple example of Applet by applet viewer tool:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet {
public void paint(Graphics g) {
g.drawString("welcome to applet", 150, 150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Using System.out.println():
System.out.println("Hello, World!");
Using System.out.print()
:
System.out.print("Hello");
Using System.out.printf()
:
System.out.printf("Name: %s, Age: %d%n", name, age);
Using System.out.format()
:
printf()
, this method formats the output but does not include automatic newline character (use %n for newline).System.out.format("Value of pi: %.2f%n", pi);
Using System.console().printf()
:
System.out.printf()
but allows interaction when running the program in a console environment.Console console = System.console();
if (console != null) {
console.printf("Hello, World!%n");
}
Using JOptionPane.showMessageDialog()
:
mport javax.swing.JOptionPane;
JOptionPane.showMessageDialog(null, "Hello, World!");
paint()
, update()
, and repaint()
methods are crucial for drawing and updating graphical content on the applet's surface. Here’s an explanation of each method and their roles:g
-The Graphics object passed to the method, which provides methods for drawing shapes, text, and images on the applet's surfacepublic void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
// Draw other shapes, images, or text as needed
}
update()
clears the background of the applet with the background color (set by setBackground()
method).g
-The Graphics object passed to the method, which allows you to redraw the applet's content.public void update(Graphics g) {
// Custom behavior before repainting
super.update(g); // Calls the default update behavior
}
repaint()
method is used to request that the applet or component should be repainted at the next available opportunity.update()
and subsequently paint()
to redraw the applet. It does not immediately repaint the applet; instead, it schedules the repaint operation to occur asynchronously.public void mouseClicked(MouseEvent e) {
// Update some state based on mouse click
// Then request a repaint to reflect the updated state
repaint();
}
SwingUtilities.invokeLater()
.BufferedImage
for off-screen rendering) to reduce flickering and improve responsiveness.paint()
, update()
, and repaint()
) provide the foundational mechanisms for rendering and updating graphical content in Java applets, allowing for dynamic and interactive visualizations within web browser environments.<applet>
tag in HTML is used to embed a Java applet into a web page.<applet>
tag and its attributes<applet>
code="AppletClassName.class"
width="width_in_pixels"
height="height_in_pixels">
Your browser does not support Java applets.
</applet>
Attributes
.class
extension. For example, if your applet class file is named MyApplet.class
, you would use code="MyApplet.class"
.Deprecated Features
<applet code="MyApplet.class" width="300" height="200">
<p>Your browser does not support Java applets.</p>
</applet>
<applet>
tag was once common for embedding Java applets in web pages, its usage has diminished due to security concerns and the evolution of web standards.drawLine()
method is used to draw a line between two points specified by their coordinates (x1, y1) and (x2, y2).// Drawing a line from (10, 20) to (100, 50)
g.drawLine(10, 20, 100, 50);
drawArc()
method draws an arc defined by a bounding rectangle (x, y, width, height), starting at startAngle
and extending for arcAngle
degrees.// Drawing an arc inside a bounding rectangle (x=50, y=50, width=100, height=100)
g.drawArc(50, 50, 100, 100, 45, 90);
fillArc()
method fills an arc with the specified properties (bounding rectangle, start angle, arc angle).// Filling an arc inside a bounding rectangle (x=50, y=50, width=100, height=100)
g.fillArc(50, 50, 100, 100, 45, 90);
// Drawing an oval inside a bounding rectangle (x=50, y=50, width=100, height=80)
g.drawOval(50, 50, 100, 80);
drawLine()
, drawArc()
, fillArc()
, drawOval()
) are typically used within the paint(Graphics g)
or paintComponent(Graphics g)
methods of a Canvas, Panel, or JPanel class.paint()
or paintComponent()
) to ensure proper rendering and to adhere to Swing's or AWT's threading rules.drawPolygon()
, drawRect()
, fillRect()
, and more.fillOval()
method draws a filled oval (ellipse) inscribed within the specified bounding rectangle.// Filling an oval inside a bounding rectangle (x=50, y=50, width=100, height=80)
g.fillOval(50, 50, 100, 80);
// Drawing a triangle with vertices at (50, 50), (100, 100), and (150, 50)
int[] xPoints = {
50,
100,
150
};
int[] yPoints = {
50,
100,
50
};
int nPoints = 3;
g.drawPolygon(xPoints, yPoints, nPoints);
fillOval()
and drawPolygon()
) are also typically used within the paint(Graphics g)
or paintComponent(Graphics g)
methods of a Canvas, Panel, or JPanel class.xPoints
and yPoints
contain enough elements to define the desired shape, and that nPoints
corresponds to the number of vertices in the polygon.Graphics.setColor()
to set the color before calling these methods to draw or fill shapes with different colors.import java.awt.*;
import javax.swing.*;
public class ShapesExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Set color for drawing and filling
g.setColor(Color.BLUE);
// Fill an oval
g.fillOval(50, 50, 100, 80);
// Set color for drawing polygon
g.setColor(Color.RED);
// Draw a polygon (triangle)
int[] xPoints = {
200,
250,
300
};
int[] yPoints = {
150,
250,
200
};
int nPoints = 3;
g.drawPolygon(xPoints, yPoints, nPoints);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Shapes Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(new ShapesExample());
frame.setVisible(true);
}
}
Made By SOU Student for SOU Students