0% found this document useful (0 votes)
2 views18 pages

Java Unit-3

The document provides an overview of Java's multithreading capabilities, including the Thread class, methods for creating and managing threads, and the life cycle of a thread. It discusses thread priority, synchronization, and communication between threads using wait and notify methods. Additionally, it covers the java.io package for input and output operations, including file handling and serialization.

Uploaded by

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

Java Unit-3

The document provides an overview of Java's multithreading capabilities, including the Thread class, methods for creating and managing threads, and the life cycle of a thread. It discusses thread priority, synchronization, and communication between threads using wait and notify methods. Additionally, it covers the java.io package for input and output operations, including file handling and serialization.

Uploaded by

venkatesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-3

1. java.lang.Thread

Introduction to Threads

 A thread is a lightweight process that allows concurrent execution in Java.


 Java supports multithreading using the java.lang.Thread class.
 Threads help in better CPU utilization and improve application performance.

Thread Class Methods

Method Description
start() Begins execution of a new thread
run() Defines the code that runs in the thread
sleep(ms) Pauses the thread for a specified time
join() Makes the current thread wait for another thread to finish
yield() Suggests the thread scheduler to give CPU to another thread
setPriority(int) Sets the priority of a thread
getPriority() Returns the priority of a thread
isAlive() Checks if a thread is still running

2. The Main Thread

What is the Main Thread?

 The first thread that executes when a Java program starts.


 It is automatically created by the JVM.
 Executes the main() method of the program.

Getting Main Thread Information


class MainThreadExample {
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
System.out.println("Main Thread: " + mainThread);
}
}
Modifying the Main Thread

class ModifyMainThread {
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
mainThread.setName("PrimaryThread");
mainThread.setPriority(Thread.MAX_PRIORITY);
System.out.println("Updated Main Thread: " + mainThread);
}
}
Output:

Main Thread: Thread[main,5,main]

Modifying the Main Thread

class ModifyMainThread {
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
mainThread.setName("PrimaryThread");
mainThread.setPriority(Thread.MAX_PRIORITY);
System.out.println("Updated Main Thread: " + mainThread);
}
}
Output:
Updated Main Thread: Thread[PrimaryThread,10,main]

3. Creation of New Threads


There are two ways to create a new thread in Java:

A. Extending the Thread Class

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running..."); }
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); }
}
Output:
Thread is running...
B. Implementing the Runnable Interface

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");
}

public static void main(String[] args) {


Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
Output:
Thread is running...
Thread Priority
What is Thread Priority?
 Each thread has a priority value (1 to 10).
 The scheduler gives preference to higher-priority threads.
 Default priority: 5
Priority Constants
Constant Value
Thread.MIN_PRIORITY 1
Thread.NORM_PRIORITY 5
Thread.MAX_PRIORITY 10

Setting and Getting Thread Priority

class ThreadPriorityExample extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName() + " - Priority: " +
Thread.currentThread().getPriority());
}

public static void main(String[] args) {


Thread t1 = new ThreadPriorityExample();
Thread t2 = new ThreadPriorityExample();

t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
}
}
Output:
Thread-0 - Priority: 1
Thread-1 - Priority: 10

 Priority helps in scheduling, but it does not guarantee execution order.


 The JVM thread scheduler handles thread execution based on priority and system
resources.

Life Cycle of a Thread in Java


The life cycle of a thread in Java refers to the various states of a thread goes through. For
example, a thread is born, started, runs, and then dies. Thread class defines the life cycle and
various states of a thread.
Flow Chart of Java Thread Life Cycle
The following diagram shows the complete life cycle of a thread.

States of a Thread Life Cycle in Java

Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Simple Thread Life Cycle Program

A thread in Java goes through various states: New, Runnable, Running, Blocked, Waiting,
and Terminated.

class ThreadLifeCycle extends Thread {

public void run() {

System.out.println("Thread is in running state.");

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Thread interrupted.");

System.out.println("Thread is terminating.");

public static void main(String[] args) {

ThreadLifeCycle t = new ThreadLifeCycle();

System.out.println("Thread is in NEW state.");

t.start();

System.out.println("Thread is in RUNNABLE state.");

}}

Output:
Thread is in NEW state.
Thread is in RUNNABLE state.

Thread is in running state.

(Thread pauses for 2 seconds)

Thread is terminating

Multithreading Concepts

1. Using isAlive() and join()

 isAlive():
o A method to check if a thread is still running.
o Returns true if the thread is alive, otherwise false.

Example:

}
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class IsAliveExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
System.out.println("Thread is alive: " + t1.isAlive());

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Thread is alive after completion: " + t1.isAlive());


}
}

Output:
Thread is alive: true
Thread-0 is running
Thread is alive after completion: false

 join():
o Allows one thread to wait until another thread completes its execution.
o Example:

java

thread.join(); // Main thread waits for the 'thread' to finish

Example Program

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class JoinExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start();
try {
t1.join(); // Main thread waits for t1 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}

t2.start();
}
}
Output: (t1 runs completely before t2 starts
Thread-0 - 1
Thread-0 - 2
Thread-0 - 3
Thread-0 - 4
Thread-0 - 5
Thread-1 - 1
Thread-1 - 2
Thread-1 - 3
Thread-1 - 4
Thread-1 - 5

2. Synchronization

 Ensures that only one thread accesses critical sections of the code at a time.
 Done using the synchronized keyword to avoid thread interference and inconsistency.
 Example:

synchronized void display() {

// Critical section

(Synchronization)Preventing Race Conditions

Suspending and Resuming Threads

 Earlier methods like suspend() and resume() were used for these purposes but are now
deprecated because they are unsafe.
 Instead, the best practice is to use flags and wait(), notify():

class SharedResource {
synchronized void printNumbers(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + (n * i));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class MyThread extends Thread {


SharedResource sr;
int num;

MyThread(SharedResource sr, int num) {


this.sr = sr;
this.num = num;
}

public void run() {


sr.printNumbers(num);
}
}

public class SynchronizationExample {


public static void main(String[] args) {
SharedResource sr = new SharedResource();
MyThread t1 = new MyThread(sr, 5);
MyThread t2 = new MyThread(sr, 10);

t1.start();
t2.start();
}
}
Output: (Numbers are printed sequentially, ensuring thread safety)
Thread-0 - 5
Thread-0 - 10
Thread-0 - 15
Thread-0 - 20
Thread-0 - 25
Thread-1 - 10
Thread-1 - 20
Thread-1 - 30
Thread-1 - 40
Thread-1 – 50

Suspending & Resuming Threads


Java 1.2 removed suspend() and resume(), so we use a flag to control execution.
class MyThread extends Thread {
private volatile boolean suspended = false;

public void run() {


for (int i = 1; i <= 5; i++) {
synchronized (this) {
while (suspended) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

synchronized void suspendThread() {


suspended = true;
}

synchronized void resumeThread() {


suspended = false;
notify();
}
}

public class SuspendResumeExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();

try {
Thread.sleep(1000);
t1.suspendThread();
System.out.println("Thread suspended");

Thread.sleep(2000);
t1.resumeThread();
System.out.println("Thread resumed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Thread-0 - 1
Thread-0 - 2
Thread suspended
(Thread paused for 2 seconds)
Thread resumed
Thread-0 - 3
Thread-0 - 4
Thread-0 - 5

Communication Between Threads: Input/Output (Reading and Writing Data)

In Java, thread communication using wait(), notify(), and notifyAll() allows synchronized
reading and writing of data between producer and consumer threads.
Example: Producer-Consumer Using Input/Output (Reading & Writing Data)

In this example:

 Producer reads input (simulated) and writes data.


 Consumer reads the produced data and processes it.

import java.util.Scanner;

class SharedBuffer {
private String data;
private boolean available = false; // To control producer-consumer flow

// Producer writes data


public synchronized void writeData(String inputData) {
while (available) { // Wait if data is not yet consumed
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data = inputData;
System.out.println("Produced: " + data);
available = true;
notify(); // Notify consumer that data is ready
}

// Consumer reads data


public synchronized String readData() {
while (!available) { // Wait if data is not yet produced
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed: " + data);
available = false;
notify(); // Notify producer to produce new data
return data;
}
}

// Producer Thread (Simulates Reading User Input)


class Producer extends Thread {
private SharedBuffer buffer;
private Scanner scanner;

Producer(SharedBuffer buffer) {
this.buffer = buffer;
this.scanner = new Scanner(System.in);
}

public void run() {


for (int i = 0; i < 3; i++) {
System.out.print("Enter data to produce: ");
String inputData = scanner.nextLine();
buffer.writeData(inputData);
}
scanner.close();
}
}

// Consumer Thread (Simulates Writing Output)


class Consumer extends Thread {
private SharedBuffer buffer;

Consumer(SharedBuffer buffer) {
this.buffer = buffer;
}

public void run() {


for (int i = 0; i < 3; i++) {
String receivedData = buffer.readData();
System.out.println("Processed Data: " + receivedData.toUpperCase());
}
}
}

public class ThreadCommunicationIO {


public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer();

Producer producer = new Producer(buffer);


Consumer consumer = new Consumer(buffer);

producer.start();
consumer.start();
}
}
Enter data to produce: hello
Produced: hello
Consumed: hello
Processed Data: HELLO
Enter data to produce: java
Produced: java
Consumed: java
Processed Data: JAVA
Enter data to produce: threading
Produced: threading
Consumed: threading
Processed Data: THREADING

How It Works:

1. Producer Thread: Reads user input from Scanner and writes it into SharedBuffer.
2. Consumer Thread: Reads data from SharedBuffer, processes it (converts to
uppercase), and prints it.
3. Thread Synchronization: Uses wait() and notify() to manage data exchange.

The java.io package in Java provides classes and interfaces for system input and output
through data streams, serialization, and file handling. It is a powerful package used for
reading and writing data (text, binary, or objects) to files, pipes, or other I/O sources.

Key Features of the java.io Package

1. File Handling:
o Work with files and directories.
o Classes: File, FileReader, FileWriter.
2. Streams:
o Handle data as input or output streams.
o Types: Byte Streams (InputStream, OutputStream) and Character Streams
(Reader, Writer).
3. Serialization:
o Store and retrieve objects as a sequence of bytes.
o Classes: ObjectInputStream, ObjectOutputStream.
4. Buffering:
o Speeds up I/O operations by using memory buffers.
o Classes: BufferedReader, BufferedWriter.

File: Represents file and directory pathnames.

 Example:

File file = new File("example.txt");


if (file.exists()) {
System.out.println("File exists!");
}
FileReader and FileWriter: For reading/writing character-based data from/to files
Example:

FileWriter writer = new FileWriter("example.txt");


writer.write("Hello, Java!");
writer.close();

FileReader reader = new FileReader("example.txt");


int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();

BufferedReader and BufferedWriter: Add buffering to character input/output for efficient


processing.
Example:
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("Buffered Writing!");
writer.newLine();
writer.close();

BufferedReader reader = new BufferedReader(new FileReader("example.txt"));


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();

4.ObjectInputStream and ObjectOutputStream: For reading and writing objects.


Example:
ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("data.obj"));
objOut.writeObject("Serializable Object");
objOut.close();

ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("data.obj"));


Object obj = objIn.readObject();
System.out.println("Read: " + obj);
objIn.close();
An applet is a special type of Java program that runs within a web browser or an applet viewer.
It was designed to create dynamic and interactive content for web applications. However,
applets have become less commonly used due to security restrictions and advancements in web
technologies like JavaScript and HTML5.

Key Features of Applets

1. Runs in a Browser: Applets are embedded in HTML pages and run using the Java
Plug-in.
2. Event-Driven: Applets interact with users through GUI elements and events.
3. Secure: Applets run in a restricted environment called the "sandbox" to prevent
harmful operations.
4. Lightweight: Applets are small and load quickly in web browsers.

Applet Life Cycle

An applet has a defined life cycle consisting of the following methods:

1. init(): Initializes the applet. Called once when the applet is loaded.
2. start(): Called every time the applet becomes visible to the user.
3. paint(Graphics g): Renders graphics or content on the applet.
4. stop(): Called when the applet is no longer visible.
5. destroy(): Cleans up resources before the applet is destroyed.
Simple Applet Example
Here's a basic example of an applet:
import java.applet.Applet;
import java.awt.Graphics;

// Simple Applet Example


public class MyApplet extends Applet {
@Override
public void init() {
System.out.println("Applet initialized");
}

@Override
public void start() {
System.out.println("Applet started");
}

@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50); // Draws text on the applet
}

@Override
public void stop() {
System.out.println("Applet stopped");
}

@Override
public void destroy() {
System.out.println("Applet destroyed");
}
}
HTML File to Run the Applet:
<html>

<body>

<applet code="MyApplet.class" width="300" height="200"></applet>

</body>

</html>
How to Run an Applet

1. Compile the Java file: javac MyApplet.java.


2. Create an HTML file with the <applet> tag (as shown above).
3. Run the applet using the appletviewer tool: appletviewer applet.html
Expected Output:

1. The applet viewer or browser will display "Hello, Applet!" at position (50, 50) on the
screen.
2. Console messages will show:

Note:

 The java.applet.Applet class and applet-related APIs are now deprecated in the latest
versions of Java, as they are no longer widely supported by browsers.
 For modern web development, consider using alternatives like JavaFX, HTML5, and
JavaScript.

In applets, the methods paint(), update(), and repaint() play a crucial role in managing the
graphical content on the applet's display area. Here's a breakdown of how these methods
work in the context of applets:

1. paint(Graphics g)

 Purpose: This method is responsible for rendering the content of the applet. It is
called whenever the applet needs to display or redraw itself.
 Characteristics:
o It is automatically invoked by the AWT when the applet is first initialized or
resized, or when the display is refreshed.
o You override this method to specify what should be drawn on the applet's
canvas.
o The parameter Graphics g is used for drawing shapes, text, and images.

Common usage

@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50); // Draw text
g.drawRect(100, 100, 50, 50); // Draw a rectangle
}

2. update(Graphics g)

 Purpose: The update() method is called to refresh the applet's display before calling
the paint() method.
 Default Behavior:
o By default, it clears the applet's background, effectively erasing previous
drawings, and then calls the paint() method.
 Custom Behavior:
o You can override update() to modify this behavior (e.g., avoid clearing the
background for smoother rendering in animations).
 How It Works:
o For example, when you call repaint(), the AWT framework triggers update()
first, which in turn calls paint().
3. repaint()

 Purpose: The repaint() method is used to request the applet to be redrawn. It does not
immediately redraw the applet but schedules a call to update() (and subsequently
paint()).
 Characteristics:
o Commonly used to refresh the applet's display when its state changes (e.g., in
response to user interaction or background processing).
o It ensures that the drawing process is handled by the AWT event thread.

Common Usage:

public void changeState() {

// Update some internal state

repaint(); // Request the applet to repaint itself

You might also like