Java U3
Java U3
SEMESTER 4
UNIT - 3
HI COLLEGE
SYLLABUS
UNIT - 3
HI COLLEGE
CONCEPT OF INPUT/OUTPUT
Besides interacting with the user, Java also supports reading and
writing data from/to files.
File I/O involves reading data from a file (input) or writing data to a file
(output).
The File class and related classes like FileReader, FileWriter,
BufferedReader, and BufferedWriter are commonly used for file I/O
operations in Java.
Here's an example that demonstrates reading from a file using
FileReader and BufferedReader
HI COLLEGE 01
READING AND WRITING USING BYTE
STREAMS IN JAVA
Open the byte stream to the source (e.g., a file) using an InputStream
class, such as FileInputStream.
Read data from the stream using the read() method. This method
returns an integer representing the byte read, or -1 if the end of the
stream is reached.
Process the data as needed.
Close the stream to release system resources using the close()
method.
HI COLLEGE 02
READING FROM BYTE STREAMS:
When writing to a byte stream, you typically follow these steps:
Open the byte stream to the destination (e.g., a file) using an
OutputStream class, such as FileOutputStream.
Write data to the stream using the write() method. This method
accepts an integer representing the byte to write.
Close the stream to flush any buffered data and release system
resources using the close() method.
HI COLLEGE 03
ELEMATARY CONCEPTS OF
INPUT/OUTPUT USING THE
CHARACTER BASED STREAMS
READING FROM CHARACTER-BASED STREAMS
To read character data from a source, you typically follow these steps:
Open the character-based stream to the source (e.g., a file) using a
Reader class, such as FileReader.
Read data from the stream using methods like read() or read(char[]
buffer). These methods return the characters read or -1 if the end of
the stream is reached.
Process the read data as needed.
Close the stream to release system resources using the close()
method.
HI COLLEGE 04
WRITING TO CHARACTER-BASED STREAMS
To write character data to a destination, you typically follow these
steps:
Open the character-based stream to the destination (e.g., a file)
using a Writer class, such as FileWriter.
Write data to the stream using methods like write(char[] buffer) or
write(String str).
Close the stream to flush any buffered data and release system
resources using the close() method.
HI COLLEGE 05
MULTI-THREADING
Multithreading is a programming technique where different parts of a
program, called threads, run concurrently.
Threads represent independent flows of execution within a program.
Threads share the same memory space, allowing them to access and
modify shared data.
Multithreading enables better resource utilization and can improve
program performance.
Synchronization mechanisms are used to coordinate thread access to
shared resources and prevent data conflicts.
Threads can communicate with each other to facilitate collaboration.
Multithreading is like having multiple employees in a company
working on different tasks simultaneously.
Proper handling of shared data and synchronization is crucial to
ensure thread safety and avoid issues like data corruption.
ADVANTAGES
Multithreading allows for efficient utilization of the CPU by
minimizing idle time.
Java's multithreading enables pausing of individual threads without
affecting other parts of the program.
Idle time, such as when a thread is waiting for network data or user
input, can be used productively by other threads.
Multithreading enables animation loops to sleep between frames
without causing the entire system to pause.
When a thread blocks in a Java program, only that specific thread
pauses while other threads continue running.
HI COLLEGE 06
THREAD CLASS AND THE RUNNABLE
INTERFACE
Java's multithreading system is based on the Thread class, its
methods, and the Runnable interface.
To create a new thread in Java, you can either extend the Thread class
or implement the Runnable interface.
Extending the Thread class means creating a new class that is a
subclass of Thread and overriding its methods as needed.
Implementing the Runnable interface involves creating a separate
class that implements the run() method defined in the interface.
The Thread class provides several methods to manage threads
effectively.
start(): This method starts the execution of a new thread, invoking the
run() method internally.
run(): You override this method to define the code that the thread will
execute.
sleep(): This method pauses the execution of the current thread for a
specified duration.
join(): It allows one thread to wait for another thread to complete its
execution.
interrupt(): This method interrupts a thread's execution, causing it to
throw an InterruptedException.
HI COLLEGE 07
THREADING CONSTRUCTOR
Java's multithreading system is based on the Thread class, its
methods, and the Runnable interface.
To create a new thread in Java, you can either extend the Thread class
or implement the Runnable interface.
Extending the Thread class means creating a new class that is a
subclass of Thread and overriding its methods as needed.
Implementing the Runnable interface involves creating a separate
class that implements the run() method defined in the interface.
The Thread class provides several methods to manage threads
effectively.
start(): This method starts the execution of a new thread, invoking the
run() method internally.
run(): You override this method to define the code that the thread will
execute.
sleep(): This method pauses the execution of the current thread for a
specified duration.
join(): It allows one thread to wait for another thread to complete its
execution.
interrupt(): This method interrupts a thread's execution, causing it to
throw an InterruptedException.
HI COLLEGE 08
THREADING CONSTRUCTOR
a) Thread():
This constructor creates a new thread without any specific name.
It sets up the thread object, but you need to override the run() method
or provide a separate Runnable object with the desired code to be
executed by the thread.
It's like creating a blank thread that you can customize later.
b) Thread(String threadName):
This constructor creates a new thread with a specified name.
The name is helpful for identifying the thread in your program and
distinguishing it from other threads.
You still need to override the run() method or provide a separate
Runnable object with the code to be executed.
c) Thread(Runnable runnableObject):
This constructor creates a new thread with a specified Runnable
object.
A Runnable object is an instance of a class that implements the
Runnable interface and defines the run() method.
The run() method contains the code that the thread will execute.
By passing a Runnable object to this constructor, you can specify the
behavior of the thread without directly extending the Thread class.
It allows you to separate the code to be executed by the thread from
the thread management itself.
HI COLLEGE 09
CREATING THREAD USING THREAD
CLASS
Derive a subclass from the Thread class:
Create a new class that extends the Thread class. This subclass will
represent your custom thread.
In Java, you can use the "extends" keyword to indicate that your class
is a subclass of Thread.
HI COLLEGE 10
Override the run() method
Inside your subclass, override the run() method from the Thread class.
The run() method contains the code that will be executed when the
thread is started.
Write the desired logic or instructions within the run() method.
HI COLLEGE 11
EXTENDING USING THREAD CLASS
HI COLLEGE 12
QUES. WRITE A PROGRAM THAT CREATES 3 THREADS
OUTPUT
HI COLLEGE 13
SLEEP METHOD
The `sleep()` method in the `Thread` class is used to pause the
execution of a thread for a specified duration of time.
It allows you to introduce a delay or wait in your program.
The `sleep()` method takes a single argument, `milliseconds`, which
represents the duration for which the thread should sleep.
The argument specifies the time in milliseconds (1 second = 1000
milliseconds).
The method throws an `InterruptedException` which is a checked
exception. This exception can occur when another thread interrupts
the sleeping thread.
The `sleep()` method should be placed inside a try-catch block to
handle the `InterruptedException` properly.
HI COLLEGE 14
THREAD PRIORITY
HI COLLEGE 15
HI COLLEGE 16
OUTPUT 1 -
HI COLLEGE 17
THREAD CLASS AND THE RUNNABLE
INTERFACE
Creating Threads
To create a new thread, you have two options:
1. Extending the Thread class: You can create a subclass that extends
the Thread class and override the `run()` method. This method
contains the code that will be executed when the thread is started.
2. Implementing the Runnable interface: Alternatively, you can
implement the Runnable interface and provide the implementation for
the `run()` method. This approach is useful when you want your class to
extend another class and still be able to create a thread.
HI COLLEGE 18
CONTROLLING THE MAIN THREAD
HI COLLEGE 19
IMPLEMENTING RUNNABLE
1. The Runnable interface in Java provides a way to create a thread by implementing
this interface in a class.
2. To implement the Runnable interface, a class needs to implement a single method
called `run()`, which is where you define the code that will be executed by the
thread.
3. The `run()` method has no arguments and does not return any value.
4. Here is an example of implementing the Runnable interface:
JOIN() METHOD
The join() method in Java allows a thread to wait for another thread to complete its
execution.
When a thread invokes the join() method on another thread, it waits until that
thread finishes its task.
HI COLLEGE 20
THREAD SYNCHRONIZATION
Whenever we declare declare any method as synchronized, it means that only one
thread can access that method at a time
While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same instance have to wait.
In this way, we ensure serialization , exclusive access & prevent race condition.
Synchronized block
This is the general form of the synchronized block: Synchronized block can be used
to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize
only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same
as the synchronized method.
synchronized(object) { // statements to be synchronized }
Object is a reference to the object being synchronized
*ME AFTER
COMPLETING JAVA
HI COLLEGE 21