0% found this document useful (0 votes)
11 views13 pages

Java Unit-4

The document explains key concepts of multithreading and multiprocessing in Java, highlighting their differences, lifecycle, and benefits. It covers the creation of threads using the Thread class and Runnable interface, thread priorities, synchronization, and stream classes for input/output operations. Additionally, it discusses reading console input and writing console output using the Console class.
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)
11 views13 pages

Java Unit-4

The document explains key concepts of multithreading and multiprocessing in Java, highlighting their differences, lifecycle, and benefits. It covers the creation of threads using the Thread class and Runnable interface, thread priorities, synchronization, and stream classes for input/output operations. Additionally, it discusses reading console input and writing console output using the Console class.
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
You are on page 1/ 13

UNIT-4

Q1) Explain the difference between Multiprocessing and Multi-threading in Java


a)
Multiprocessing and multithreading are two paradigms of parallel execution in
computing, each designed to improve the performance and efficiency of applications.
They achieve concurrency in different ways and have distinct characteristics. Here’s a
detailed comparison of the two:
Definitions:
 Multiprocessing:
o Multiprocessing refers to the use of two or more CPUs (or cores) in a
single computer system to execute multiple processes simultaneously.
Each process runs in its own memory space, allowing them to operate
independently.
 Multithreading:
o Multithreading involves multiple threads within a single process. Threads
share the same memory space and resources of the process but execute
independently, allowing for concurrent execution of tasks.
Q2) Explain about Life Cycle of Multi-threading in Java
a)
Multithreading is a programming paradigm that allows multiple threads to exist within a
single process, enabling concurrent execution of tasks.
 A thread is a lightweight subprocess, the smallest unit of processing that can be
scheduled by the operating system.
 By utilizing multithreading, applications can perform multiple operations
simultaneously, improving performance, responsiveness, and resource
utilization.
 In Java, multithreading is a core feature that helps developers build efficient
applications that can handle various tasks like processing user inputs, performing
background calculations, and managing multiple client requests in web
applications without blocking the user interface or slowing down performance.
Key Benefits of Multithreading
1. Concurrency: Multithreading allows multiple threads to run concurrently, making
it possible to perform multiple tasks simultaneously.
2. Resource Sharing: Threads within the same process share the same memory
space, which allows for easier communication and resource sharing between
threads compared to separate processes.
3. Improved Performance: Multithreading can enhance performance, particularly
on multi-core processors, where threads can be executed in parallel.
Life Cycle of Multi-Threading
In Java, a thread goes through several states during its lifecycle, managed by the Java
Virtual Machine (JVM). Understanding the thread lifecycle is crucial for effective
multithreading. The main states are:

1. New State:
o When a thread is created, it is in the New state. This is the initial state of
the thread, and it is not yet started.
o In this state, a thread object is created, but the thread has not started
running.
Example:
Thread thread = new Thread(); // Thread is in the New state
2. Runnable State:
 When the start() method is called on a thread, it transitions to the Runnable
state. In this state, the thread is ready to run and waiting for CPU time.
 A thread can also be in this state if it has been preempted by the CPU.
Example:
thread.start(); // Thread transitions to Runnable state
3. Blocked State:
 A thread enters the Blocked state when it is waiting to acquire a lock (monitor) to
enter a synchronized block or method held by another thread.
 In this state, the thread cannot proceed until the lock is released.
4. Waiting State:
 A thread is in the Waiting state when it waits indefinitely for another thread to
perform a particular action. This can occur when:
o The thread calls Object.wait(), Thread.join()
 The thread remains in this state until another thread signals it to wake up.
5. Timed Waiting State:
 A thread enters the Timed Waiting state when it is waiting for another thread to
perform an action for a specified period. This can happen when:
o The thread calls Thread.sleep(millis)
o
 The thread will return to the Runnable state when the specified time elapses.
6. Terminated State:
 A thread enters the Terminated state when it has completed its execution, either
normally or abnormally, or when it is forcibly stopped.
 Once a thread is in this state, it cannot be restarted.
Ex:
class first extends Thread
{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}

class second extends Thread


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
class thread1
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
f.start();
s.start();
}
}
Q3) Explain about Multi Threading with Thread Class and Runnable Interface
A)
Multithreading is a programming paradigm that allows multiple threads to exist within a
single process, enabling concurrent execution of tasks.
 A thread is a lightweight sub process, the smallest unit of processing that can be
scheduled by the operating system.
 By utilizing multithreading, applications can perform multiple operations
simultaneously, improving performance, responsiveness, and resource
utilization.
 In Java, multithreading is a core feature that helps developers build efficient
applications that can handle various tasks like processing user inputs, performing
background calculations, and managing multiple client requests in web
applications without blocking the user interface or slowing down performance.
Key Benefits of Multithreading
1. Concurrency: Multithreading allows multiple threads to run concurrently, making it
possible to perform multiple tasks simultaneously.
2. Resource Sharing: Threads within the same process share the same memory
space, which allows for easier communication and resource sharing between
threads compared to separate processes.
3. Improved Performance: Multithreading can enhance performance, particularly on
multi-core processors, where threads can be executed in parallel.
Multithread Programs can developed through 2 Ways
a) Thread Class
b) Runnable Interface

1. Using the Thread Class


=> It is a Super Class which is imported from the lang Package(import java.lang.*)
=> When you extend the Thread class, you create a new thread by overriding the run()
method, which contains the code that will be executed by the thread.
Syntax:
Class classname extends Thread
{
Code;
}
Example:
class first extends Thread
{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}

class second extends Thread


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
class thread1
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
f.start();
s.start();
}
}
2. Using the Runnable Interface
Implementing the Runnable interface provides a more flexible approach to creating
threads, allowing you to separate the thread's behavior from the thread's execution.
This is useful if you want to extend another class.
Syntax:
Class classname implements Runnable
{
Code
}
Ex:

class first implements Runnable


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}

class second implements Runnable


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
class thread1
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
t1.start();
t2.start();
}
}
Q4) Explain about Thread Priorities in Java
A) Thread Priorities in Java
 Thread priorities in Java are used to indicate the importance of a thread relative
to others.
 They help the Java Virtual Machine (JVM) and the underlying operating system
manage how threads are scheduled for execution.
 While Java provides a way to set thread priorities, it’s important to understand
that the actual scheduling of threads is platform-dependent and may not strictly
follow the specified priorities.
Thread Priority Levels
Java defines three constants in the Thread class for setting thread priorities:
 Thread.MIN_PRIORITY (value 1): Represents the lowest priority.
 Thread.NORM_PRIORITY (value 5): Represents the default priority assigned to
threads.
 Thread.MAX_PRIORITY (value 10): Represents the highest priority.

class first extends Thread


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}

class second extends Thread


{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
class thread1
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
f.setPriority(10);
f.start();
s.start();
}
}
Q5) Explain about Synchronized or Synchronization in Multithreading
A)

Multithreading:
o Multithreading involves multiple threads within a single process. Threads
share the same memory space and resources of the process but execute
independently, allowing for concurrent execution of tasks.

Synchronization in Multithreading
1. Synchronization in Java is a mechanism that ensures that only one thread can
access a resource at a time, preventing data inconsistency and race conditions
when multiple threads access shared data.
Synchronized Methods: You can declare a method as synchronized using the
synchronized keyword. This ensures that only one thread can execute that method on a
particular object at a time.
Syntax:
Synchronized returntype methodname( )
{
}
Ex:
public synchronized void increment()
{
count++;
}
Note: Write the Example in Notes

Q6) Explain about Stream Classes in Java


(or)
Explain about Byte Stream and Character Stream Classes in Java
A)
Java Stream Classes

 The Java Input/Output (I/O) is a part of java.io package.


 This package contains a relatively large number of classes that support input and
output operations.
 These classes may be categorized into groups based on the data type on which
they operate.

1. Byte Stream Classes that provide support for handling I/O operations on bytes.
2. Character Stream Classes that provide support for managing I/O operations
on characters.

Figure : Classification of Java Stream Classes

 These two groups may further be classified based on their purpose.


 The Figure shows how stream classes are grouped based on their functions.
 Byte stream and Character stream classes contain specialized input and output
stream classes to deal with input and output operations independently on various
types of streams.
Byte Stream Classes
There are two main types of byte stream classes:
1. InputStream: This is the superclass for all byte-based input stream classes in
Java. It provides a way to read bytes from a source, such as a file, memory
buffer, or network socket.
2. OutputStream: This is the superclass for all byte-based output stream classes. It
provides a way to write bytes to a destination, like a file, memory buffer, or
network socket.

Common Byte Stream Classes and Their Uses


1. FileInputStream and FileOutputStream
 These classes are used to read and write files as raw bytes.
 FileInputStream reads bytes from a file.
 FileOutputStream writes bytes to a file.
2. BufferedInputStream and BufferedOutputStream
 These classes wrap other input/output streams and add buffering to improve
efficiency by reducing the number of read/write operations.
 BufferedInputStream reads bytes into a buffer, which allows reading multiple
bytes at a time instead of one-by-one.
 BufferedOutputStream writes bytes into a buffer before sending them to the
output stream.
3. DataInputStream and DataOutputStream
 These classes allow you to read and write primitive data types (like int, float,
double, etc.) in a machine-independent way.
 DataInputStream reads bytes from an input stream and converts them to Java
primitive data types.
 DataOutputStream writes Java primitive data types as bytes to an output
Stream
read() => It is a method Used to retrieve the Data from the File
write() => It is a Method Used to store the data at particular File
close() => It is a method used to Close the File after Writing or Reading

Example:
Program to Store and Display the Data through FileInputStream and
FileOutputStream
import java.io.*;
class f1
{
public static void main(String args[ ]) throws IOException
{
FileOutputStream fos=new FileOutputStream("hari.txt");
String str="Arunachala Siva";

for(int i=0;i<str.length();i++)
{
fos.write(str.charAt(i));
}

fos.close();

FileInputStream fis=new FileInputStream("hari.txt");

int read;

while((read=fis.read())!=-1)
{
System.out.print((char)read);
}
}
}

Character Stream Classes:

 Java offers another type of streams called Character Streams, which are used to
read from the input device and write to the output device in units of 16-bit (Unicode)
characters.
 In some cases, character streams are more efficient than byte streams. The oldest
version of Java (Java 1.0) did not include character streams and, thus, all I/O was
byte-oriented. Character streams were added by Java 1.1, and certain byte-
oriented classes and methods were deprecated.
 Character streams are defined by using two class hierarchies.
 At the top there are two abstract classes, Reader and Writer. These abstract
classes handle Unicode character (16-bit) streams.
 Java has several concrete subclasses of each of these.
 The abstract classes Reader and Writer define several key methods that the other
stream classes implement.
 Two of the most important methods are read() and write(), which read and write
characters of data, respectively. These methods are overridden by derived stream
classes.
Reader Stream Classes
 The Reader class contains methods that are identical to those available in
the InputStream class, except Reader is designed to handle characters.
 Therefore, Reader classes can perform all the functions implemented by
the InputStream classes.
 The hierarchy of Reader character stream classes is shown below:

Hierarchy of Reader Classes

Writer Stream Classes


 The Writer class contains methods that are identical to those available in
the OutputStream class, except Writer is designed to handle characters.
 Therefore, Writer classes can perform all the functions implemented by
the OutputStream classes.
 The hierarchy of Writer character stream classes is shown below:
Hierarchy of Writer Classes

Example:
import java.io.*;
class f2
{
public static void main(String args[ ]) throws IOException
{
FileWriter fw=new FileWriter("hari1.txt");
String str="Arunachala Siva";
for(int i=0;i<str.length();i++)
{
fw.write(str.charAt(i));
}
fw.close();
FileReader fr=new FileReader("hari1.txt");
int read;
while((read=fr.read())!=-1)
{
System.out.print((char)read);
}
}
}
Q7) Explain about Reading Console Input and Writing Console Output
A)

 To obtain console input and output you can use the methods provided by
the console class. It offers ways to read text messages and passwords.
 The Console Class provides an Interface to the system console, allowing
interaction with Reading and Writing
 It is used to read from and write to the Console
 Console is primarily a convenience class because most of its functionality
is available through “System.in” and “System.out”
 The java.io Console class is attached with system console internally.

Note:
Write Example from Question No 1 or Question No 2

You might also like