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

Java U3

Uploaded by

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

Java U3

Uploaded by

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

JAVA

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

READING FROM BYTE STREAMS:

When reading from a byte stream, you typically follow


these steps:

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.

AUTOMATICALLY CLOSING A FILE


After the execution of the try block, regardless of whether an
exception occurs or not, the FileInputStream will be automatically
closed due to the try-with-resources statement. This ensures that
system resources are released properly.

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.

SOME KEY METHODS PROVIDED BY THE THREAD


CLASS ARE:

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.

SOME KEY METHODS PROVIDED BY THE THREAD


CLASS ARE:

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.

Create an instance of the subclass:


Instantiate your subclass by creating an object of it.
This object represents an instance of your custom thread.

Call the start() method


To start the execution of your thread, call the start() method on the
thread object.
The start() method internally calls the run() method you have
overridden.
Avoid directly calling the run() method as it won't create a new thread
and execute in parallel.

HI COLLEGE 11
EXTENDING USING THREAD CLASS

THREADS BY IMPLEMENTING RUNNABLE


INTERFACE

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

In Java, each thread is assigned a priority, which determines the order


in which it is scheduled to run.
By default, threads have the same priority called NORM_PRIORITY,
and they are served using the First-Come-First-Served (FCFS) policy.
Java allows users to change the priority of threads using the
`setPriority()` method. The syntax is:
`ThreadName.setPriority(intNumber)`
There are three predefined priority levels in Java:

MIN_PRIORITY with a value of 1


NORM_PRIORITY with a value of 5
MAX_PRIORITY with a value of 10

To set a thread's priority, use the `setPriority()` method, which is a


member of the Thread class. The syntax is:
`threadObject.setPriority(intLevel)`
The `intLevel` parameter specifies the new priority for the thread, and
it should be within the range of MIN_PRIORITY and MAX_PRIORITY.
To return a thread to the default priority, you can specify
NORM_PRIORITY, which is currently set to 5.
You can obtain the current priority setting of a thread by calling the
`getPriority()` method of the Thread class.
The syntax is:
int currentPriority = threadObject.getPriority()`
The `getPriority()` method returns the current priority level of the
thread as an integer value.

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.

The Main Thread


When a Java program starts, it immediately begins executing in a thread
called the main thread. The main thread is created automatically and is
responsible for executing the main method of your program. It serves as
the starting point for creating other threads and often performs essential
shutdown actions.

Controlling the Main Thread


Although the main thread is created automatically, you can control it by
obtaining a reference to it using the `currentThread()` method of the
Thread class. This method is a public static member and returns a
reference to the thread in which it is called. By obtaining a reference to
the main thread, you can apply thread-related operations to it just like
any other Thread

HI COLLEGE 18
CONTROLLING THE MAIN THREAD

The code demonstrates how to control the main thread in Java.


The `Thread.currentThread()` method returns a reference to the
current thread, which is the main thread in this case.
The `setName()` method is used to change the name of the thread. In
this example, the name is changed to "My Thread".
The `System.out.print()` statements are used to print information
about the current thread, such as its name before and after the name
change.
The main thread enters a loop and counts down from 5 to 1.
After printing each number, the thread sleeps for 1 second using the
`Thread.sleep()` method.
The `sleep()` method can throw an `InterruptedException` if the
thread gets interrupted during the sleep period.
If an `InterruptedException` occurs, the catch block is executed, and a
message is printed indicating that the main thread was interrupted.
By controlling the main thread, we have the ability to modify its
properties, handle interruptions, and customize its behavior based on
our requirements.

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:

class MyThread implements Runnable {


// other class members
public void run() {
// code for thread execution
}
}
5. To create a thread using the Runnable implementation
follow these steps:
Create an instance of the class that implements the Runnable interface.
Create a Thread object, passing the instance of the class as a parameter to the
Thread constructor.
Start the execution of the thread using the `start()` method of the Thread class.

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

You might also like