0% found this document useful (0 votes)
2 views

Multithreaded Programming in Java.docx Chatgpt

The document provides an overview of multithreaded programming in Java, covering the Thread class, Runnable interface, synchronization techniques, interthread communication, and deadlock scenarios. It also discusses I/O streams, including byte and character streams, and demonstrates file handling and console input/output. Examples are provided for each concept to illustrate their implementation in Java.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Multithreaded Programming in Java.docx Chatgpt

The document provides an overview of multithreaded programming in Java, covering the Thread class, Runnable interface, synchronization techniques, interthread communication, and deadlock scenarios. It also discusses I/O streams, including byte and character streams, and demonstrates file handling and console input/output. Examples are provided for each concept to illustrate their implementation in Java.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Multithreaded Programming in Java

1. Thread Class:

 The Thread class in Java is part of the java.lang package. It represents a single thread
of execution.
 Threads can be created by either:
1. Extending the Thread class: Create a subclass of Thread and override its run()
method.
2. Implementing the Runnable interface: This is more flexible as it allows a class
to extend another class while still providing thread functionality.

Example using Thread class:

java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}

2. Runnable Interface:

 The Runnable interface represents a task that can be executed by a thread. It has only one
method: run().
 A class can implement the Runnable interface and pass it to a Thread object.

Example using Runnable:

java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}

public class RunnableDemo {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // Starts the thread
}
}

3. Synchronization:

 Synchronization is a technique used to prevent thread interference when multiple


threads access shared resources.
 Java provides two ways to ensure synchronization:
1. Using synchronized methods: By marking a method as synchronized, only one
thread can execute it at a time.
2. Using synchronized block (statement): You can synchronize specific blocks of
code to ensure that only one thread can execute it at a time.

Example of synchronized method:

java
CopyEdit
class Counter {
private int count = 0;

// Synchronize the method to ensure only one thread can access it


public synchronized void increment() {
count++;
}

public int getCount() {


return count;
}
}

Example of synchronized block (statement):

java
CopyEdit
class Counter {
private int count = 0;

public void increment() {


synchronized(this) { // Lock this object for synchronization
count++;
}
}

public int getCount() {


return count;
}
}

4. Interthread Communication:

 Interthread communication allows threads to communicate with each other using methods
like wait(), notify(), and notifyAll() (these are methods in the Object class).
 These methods allow threads to communicate and coordinate with each other (e.g., one
thread can wait until another thread signals it to proceed).

Example of interthread communication:

java
CopyEdit
class SharedResource {
synchronized void printMessages() throws InterruptedException {
System.out.println("Message from thread: " +
Thread.currentThread().getName());
Thread.sleep(1000); // Simulating some work
}
}

class ThreadOne extends Thread {


private SharedResource resource;

public ThreadOne(SharedResource resource) {


this.resource = resource;
}

public void run() {


try {
resource.printMessages();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class CommunicationDemo {


public static void main(String[] args) {
SharedResource resource = new SharedResource();
ThreadOne t1 = new ThreadOne(resource);
t1.start();
}
}

5. Deadlock:

 Deadlock occurs when two or more threads are blocked forever because they are waiting
for each other to release resources.
 A deadlock situation typically involves four conditions: mutual exclusion, hold and wait,
no preemption, and circular wait.

Example of deadlock:

java
CopyEdit
class A {
synchronized void methodA(B b) {
System.out.println("Thread 1: Holding lock A...");
try { Thread.sleep(1000); } catch (Exception e) {}
System.out.println("Thread 1: Waiting for lock B...");
b.last();
}

synchronized void last() {


System.out.println("Inside A's last method");
}
}

class B {
synchronized void methodB(A a) {
System.out.println("Thread 2: Holding lock B...");
try { Thread.sleep(1000); } catch (Exception e) {}
System.out.println("Thread 2: Waiting for lock A...");
a.last();
}

synchronized void last() {


System.out.println("Inside B's last method");
}
}

public class DeadlockDemo {


public static void main(String[] args) {
final A a = new A();
final B b = new B();

Thread t1 = new Thread() {


public void run() {
a.methodA(b);
}
};

Thread t2 = new Thread() {


public void run() {
b.methodB(a);
}
};

t1.start();
t2.start();
}
}

I/O Streams in Java

1. Concepts of Streams:

 A stream is a sequence of data elements that are read from or written to an I/O device.
 Java supports two types of streams: byte streams and character streams.

2. Stream Classes:
 Byte Streams: These handle raw binary data (e.g., image files, audio files).
o Classes: InputStream, OutputStream, FileInputStream, FileOutputStream.
 Character Streams: These handle character data and are designed for reading and
writing text.
o Classes: Reader, Writer, FileReader, FileWriter.

3. Byte Stream:

 FileInputStream and FileOutputStream are used for byte-oriented I/O.

Example of byte stream:

java
CopyEdit
import java.io.*;

public class ByteStreamDemo {


public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
fis.close();
fos.close();
}
}

4. Character Stream:

 FileReader and FileWriter are used for character-oriented I/O.

Example of character stream:

java
CopyEdit
import java.io.*;

public class CharacterStreamDemo {


public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");
int charData;
while ((charData = fr.read()) != -1) {
fw.write(charData);
}
fr.close();
fw.close();
}
}
5. Reading Console Input and Writing Console Output:

 You can use System.in for reading input from the console and System.out for printing
output to the console.

Example for console input and output:

java
CopyEdit
import java.util.Scanner;

public class ConsoleIO {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}
}

6. File Handling:

 File handling in Java is done through classes in the java.io package, such as File,
FileReader, FileWriter, BufferedReader, and BufferedWriter.

Example of basic file handling:

java
CopyEdit
import java.io.*;

public class FileHandling {


public static void main(String[] args) throws IOException {
File file = new File("example.txt");

// Writing to file
FileWriter writer = new FileWriter(file);
writer.write("Hello, this is a file!");
writer.close();

// Reading from file


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

You might also like