Multithreaded Programming in Java public static void main(String args[]) {
MyThread t = new MyThread();
Multithreading is a feature in Java that allows a program to perform multiple tasks
simultaneously. A thread is a lightweight process that runs independently within a program.
[Link]();
Multithreading improves CPU utilization, program performance, and responsiveness. Java
provides built-in support for multithreaded programming through the Thread class and Runnable }
interface.
}
In Java, threads can run concurrently and share resources like memory, but proper
synchronization is required to avoid conflicts. Explanation
1. Thread Class run() method contains the code executed by the thread
Java provides a Thread class in the [Link] package to create and manage threads. start() method starts the thread execution
To create a thread using the Thread class, we need to extend the Thread class and override the Thus, the Thread class provides an easy way to create and control threads in Java.
run() method.
2. Runnable Interface
Syntax
Another way to create threads is by implementing the Runnable interface.
Java
The Runnable interface contains only one method:
Copy code
Java
class MyThread extends Thread {
Copy code
public void run() {
public void run();
// code executed by thread
Syntax
}
Java
}
Copy code
Example
class MyClass implements Runnable {
Java
public void run() {
Copy code
// thread code
class MyThread extends Thread {
}
public void run() {
}
[Link]("Thread is running");
Example
}
Java
class Counter {
Copy code
int count = 0;
class MyClass implements Runnable {
synchronized void increment() {
public void run() {
count++;
[Link]("Thread using Runnable interface");
}
}
}
public static void main(String args[]) {
Thus, synchronization helps prevent thread interference and ensures data consistency.
MyClass obj = new MyClass();
4. Using Synchronized Methods
Thread t = new Thread(obj);
A synchronized method ensures that only one thread can execute the method at a time.
[Link]();
Syntax
}
Java
}
Copy code
Advantages of Runnable Interface
synchronized void methodName() {
Allows a class to extend another class
// critical section
Better for large programs
}
Promotes flexible design
Example
Thus, the Runnable interface is commonly used for creating threads in modern Java programs.
Java
3. Synchronization
Copy code
Synchronization is a mechanism used to control the access of multiple threads to shared
resources. class Table {
When multiple threads try to access the same resource simultaneously, it may cause data synchronized void printTable(int n) {
inconsistency. Synchronization ensures that only one thread can access a resource at a time.
for(int i=1;i<=5;i++) {
Java provides synchronization using the synchronized keyword.
[Link](n*i);
Example
}
Java
}
Copy code
}
If multiple threads call this method, only one thread executes it at a time. Inter-thread communication allows threads to communicate with each other and coordinate their
execution.
Thus, synchronized methods protect shared resources from concurrent access.
Java provides three methods for this purpose:
5. Using Synchronized Statement
wait()
Instead of synchronizing the whole method, we can synchronize only a specific block of code
using a synchronized statement. notify()
Syntax notifyAll()
Java These methods are defined in the Object class.
Copy code Example
synchronized(object) { Java
// critical section Copy code
} class Test {
Example synchronized void print() {
Java try {
Copy code wait();
class Test { }
void print(int n) { catch(Exception e) {}
synchronized(this) { [Link]("Thread resumed");
for(int i=1;i<=5;i++) { }
[Link](n*i); }
} Explanation
} wait() makes thread wait
} notify() wakes up waiting thread
} notifyAll() wakes all waiting threads
This allows better performance because only a small part of the code is locked. Thus, inter-thread communication helps threads cooperate with each other efficiently.
6. Inter-Thread Communication 7. Deadlock
A deadlock occurs when two or more threads are waiting for each other to release resources, [Link]("Thread 2");
and none of them can proceed.
}
In this situation, the program stops execution permanently.
}
Example Concept
}
Thread 1 holds Resource A and waits for Resource B.
}
Thread 2 holds Resource B and waits for Resource A.
Ways to Prevent Deadlock
Both threads wait forever, causing a deadlock.
Avoid nested locks
Example Code
Use proper lock ordering
Java
Use timeout mechanisms
Copy code
Reduce resource dependency
class A {}
Thus, deadlock is a serious problem in multithreaded programs and must be handled carefully.I/
class B {} O Streams in Java
class Test { Input/Output (I/O) Streams in Java are used to perform input and output operations such as
reading data from input devices and writing data to output devices.
A a = new A();
In Java, a stream is a sequence of data. It represents a flow of data between a program and an
B b = new B(); input or output source such as a file, keyboard, or network.
void method1() { Java provides a powerful I/O system through the [Link] package, which contains many classes
used for reading and writing data.
synchronized(a) {
I/O streams help programmers to:
synchronized(b) {
Read data from input sources
[Link]("Thread 1");
Write data to output destinations
}
Handle files and external data efficiently
}
1. Concept of Streams
}
A stream is a flow of data that moves from a source to a destination.
void method2() {
Streams are mainly of two types:
synchronized(b) {
Input Stream – used to read data
synchronized(a) {
Output Stream – used to write data
import [Link].*;
Example
class Test {
Keyboard Program (Input Stream)
public static void main(String args[]) throws Exception {
Program Screen (Output Stream)
FileInputStream fin = new FileInputStream("[Link]");
Diagram Concept
int i;
Copy code
while((i = [Link]()) != -1) {
Input Device Input Stream Program Output Stream Output Device
[Link]((char)i);
In Java, streams are used for file operations, console input/output, and network communication.
}
2. Stream Classes in Java
[Link]();
Java provides many stream classes in the [Link] package.
}
The main base classes are:
}
Input Stream Classes
3. Byte Streams and Character Streams
InputStream
Java I/O streams are divided into two main categories.
FileInputStream
Byte Streams
BufferedInputStream
Byte streams are used to handle binary data such as images, audio, and video files.
DataInputStream
They read and write 8-bit bytes.
Output Stream Classes
Main classes:
OutputStream
InputStream
FileOutputStream
OutputStream
BufferedOutputStream
FileInputStream
DataOutputStream
FileOutputStream
These classes provide methods to read and write different types of data.
Example
Example
Java
Java
Copy code
Copy code
import [Link].*;
FileReader fr = new FileReader("[Link]");
class Test {
int i;
public static void main(String args[]) throws Exception {
while((i = [Link]()) != -1) {
FileInputStream fin = new FileInputStream("[Link]");
[Link]((char)i);
int i;
}
while((i = [Link]()) != -1) {
[Link]();
[Link]((char)i);
}
}
}
[Link]();
Thus, byte streams are used for binary data, while character streams are used for text data.
}
4. Reading Console Input and Writing Console Output
}
Java allows reading input from the keyboard and displaying output on the screen.
Character Streams
Console input can be taken using classes like:
Character streams are used to handle text data such as characters and strings.
Scanner
They read and write 16-bit Unicode characters.
BufferedReader
Main classes:
InputStreamReader
Reader
Using Scanner Class
Writer
Example:
FileReader
Java
FileWriter
Copy code
Example
import [Link];
Java
class Test {
Copy code
public static void main(String args[]) {
import [Link].*;
Scanner sc = new Scanner([Link]);
class Test {
[Link]("Enter your name:");
public static void main(String args[]) throws Exception {
String name = [Link]();
[Link]("File created");
[Link]("Hello " + name);
}
}
else {
}
[Link]("File already exists");
Console Output
}
Java displays output using:
}
[Link]()
}
[Link]()
Writing to a File
Example:
Java
Java
Copy code
Copy code
import [Link].*;
[Link]("Welcome to Java");
class Test {
Thus, console I/O allows interaction between user and program.
public static void main(String args[]) throws Exception {
5. File Handling in Java
FileWriter fw = new FileWriter("[Link]");
File handling in Java is used to create, read, write, and delete files.
[Link]("Hello Java");
Java provides the File class in the [Link] package to perform file operations.
[Link]();
Creating a File
}
Example:
}
Java
Reading from a File
Copy code
Java
import [Link].*;
Copy code
class Test {
import [Link].*;
public static void main(String args[]) throws Exception {
class Test {
File f = new File("[Link]");
public static void main(String args[]) throws Exception {
if([Link]()) {
FileReader fr = new FileReader("[Link]");
int i;
while((i = [Link]()) != -1) {
[Link]((char)i);
[Link]();
Advantages of File Handling
Stores data permanently
Allows reading and writing data easily
Supports large data storage
Helps manage files efficiently
Thus, Java I/O streams and file handling provide powerful tools for managing data input and
output in programs. Make as PDF