0% found this document useful (0 votes)
0 views11 pages

Java Unit IV

The document discusses the differences between multiprocessing and multithreading, highlighting their concepts, execution, and resource requirements. It also outlines the various states of threads in Java, methods for creating threads, handling interruptions, and setting thread priorities. Additionally, it covers Java's stream-based I/O, including byte and character streams, file handling, and the Java Console class for console input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views11 pages

Java Unit IV

The document discusses the differences between multiprocessing and multithreading, highlighting their concepts, execution, and resource requirements. It also outlines the various states of threads in Java, methods for creating threads, handling interruptions, and setting thread priorities. Additionally, it covers Java's stream-based I/O, including byte and character streams, file handling, and the Java Console class for console input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT-IV

MULTITHREADING:
 Differences between Multiprocessing and Multithreading:
Multiprocessing:
A multiprocessing system has more than two processors. The CPUs are added to the system that
helps to increase the computing speed of the system. Every CPU has its own set of registers and
main memory.

Multithreading:
Multithreading is a program execution technique that allows a single process to have multiple code
segments (like threads|). It is also running concurrently within the “context” of that process.

Factor Multiprocessing Multithreading

Multiple processors/CPUs are


Multiple threads are created of a process to be
added to the system to increase
Concept executed in a parallel fashion to increase the
the computing power of the
throughput of the system.
system.

Parallel Multiple processes are executed Multiple threads are executed in a parallel
Action in a parallel fashion. fashion.

Multiprocessing can be classified


Categories into symmetric and asymmetric No such classification present for multithreading.
multiprocessing.

Process creation is time-


Time Thread creation is easy and is time savvy.
consuming.

In multiprocessing, many
In multithreading, many threads are executed
Execution processes are executed
simultaneously.
simultaneously.

In multiprocessing, a separate
Address In multithreading, a common address space is
address space is created for each
space used for all the threads.
process.

Multiprocessing requires a
Multithreading requires less time and few
Resources significant amount of time and
resources to create.
large number of resources.

1|Page
2|Page
 Thread States and Thread Life Cycle in Java:
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of
the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.

1. New
Thread state for a thread that has not yet started.
public static final Thread. State NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but
it may be waiting for other resources from the operating system such as a processor.
public static final Thread. State RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a
monitor lock to enter a synchronized block/method or re-enter a synchronized block/method after calling
Object.wait().
public static final Thread. State BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following
methods:
 Object.wait with no timeout
 Thread.join with no timeout
 LockSupport.park
public static final Thread.State WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to
calling one of the following methods with a specified positive waiting time:
 Thread.sleep
 Object.wait with timeout
 Thread.join with timeout
 LockSupport.parkNanos
 LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
3|Page
Declaration: public static final Thread.State TERMINATED

 Creating Threads:
 A thread is similar to a program that has a single flow control.
 We can create a thread in two ways
(1). By extending Thread class
(2). By implementing Runnable interface

(1). By extending Thread class:

* Define a class and extends Thread class


* Override run () it contains the code (some other methods start (), sleep () etc.,)

Example:
class MyThread extends Thread
{
public void run ()
{
System.out.println(“This is my first thread and it is running”);
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
t1.start();
}
}

Output: This is my first thread and it is running

(2). By implementing Runnable interface:

* Define a class that implements Runnable interface.


* run() method overriding and it contains the code.

Example:
class MyRunnable implements Runnable
{
public void run ()
{
System.out.println(“First thread running”);
}
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t1=new Thread(r);
t1.start();
}
}
Output: First thread running

4|Page
 Thread Interrupted:
Thread Interruption in Java:

Thread interruption is a mechanism to signal a thread to stop its execution. It's not a forceful
termination but rather a polite request.

Methods:

1. interrupt(): Interrupts the thread.


2. isInterrupted(): Checks if the thread is interrupted.
3. interrupted(): Checks if the current thread is interrupted.

Thread Interruption Scenarios:

1. Runnable: Interrupting a runnable thread will set the interrupted flag.


2. Sleeping: Interrupting a sleeping thread will throw InterruptedException.
3. Blocked: Interrupting a blocked thread will not affect its state.

Handling Interruption:

1. Catch InterruptedException: Handle interruption in catch block.


2. Check interrupted flag: Use isInterrupted() or interrupted() to check interruption.
3. Restore interrupted status: Call Thread.currentThread().interrupt() after handling.

 Thread Priorities:
As we already know java being completely object-oriented works within a multithreading environment in
which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a
thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the
thread or it can be given by the programmer explicitly.
Priorities in threads is a concept where each thread is having a priority which in layman’s language one
can say every object is having priority here which is represented by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 1.
 Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:


1. public static int MIN_PRIORITY=1
2. public static int NORM_PRIORITY=5
3. public static int MAX_PRIORITY=10
Let us discuss it with an example to get how internally the work is getting executed. Here we will be
using the knowledge gathered above as follows:
 We will use currentThread() method to get the name of the current thread. User can also
use setName() method if he/she wants to make names of thread as per choice for understanding
purposes.
 getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.
Let us do discuss how to get and set priority of a thread in java.
5|Page
1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the
priority of thread to the value newPriority. This method throws IllegalArgumentException if value of
parameter newPriority goes beyond minimum(1) and maximum(10) limit.

6|Page
**********

7|Page
Stream based I/O(java.io):
 The stream classes-Byte streams and character streams:
Java offers two types of streams:
1.Byte streams.
2.Character streams

1. Byte Streams:
Byte Stream classes are used to read bytes from and write bytes to an input stream. To put it another
way, Byte Stream classes read and write 8-bit data.
Using Byte Stream classes, we can save video, audio, characters, and so on. The java.io package
contains these classes.
Byte Java streams have a three-phase mechanism:
 Split: A spliterator divides the input data source into a stream. The Java Spliterator interface is an
internal iterator that divides the stream into smaller parts for traversal.
 Apply: The elements in the stream are processed.
 Combine: After the elements have been processed, they are combined once more to produce a single
result.

The ByteStream classes are classified into two types:


(a). InputStream
(b). OutputStream
These are the abstract super classes for all Input/Output stream classes.
(a). InputStream:
This type of java stream reads data from a source. An InputStream can read data from a file, network
connection, or any other I/O device. An InputStream can be used to read data from a file
Syntax of InputStream:
FileInputStreamsourceStream = new FileInputStream("pathtofile");
(b). OutputStream:
The outputstream is a java stream that takes data from a Java program and sends or writes it to the
destination (data sink). A data flow out of a program is represented by an output. The output stream
connects a Java program to a data sink. A Java program writes or sends data to the data sink.
The data flow from a data source to a Java program via an input stream. The data flow from a Java
program to a data sink via an output stream.
Syntax of OutputStream:
FileOutputStreamtargetStream = new FileOutputStream("path_to_file");
2. Character Stream:
The Character stream is used for 16-bit Unicode input and output operations. Character streams
would be advantageous if we wanted to copy a text file containing characters from one source to
8|Page
another using streams because it deals with characters. Java characters are 2 bytes (or 16 bits) in
size.CharacterStream classes are provided by the java.io package to overcome the limitations of
ByteStream classes, which can only handle 8-bit bytes and are incompatible with working directly
with Unicode characters. CharacterStream classes are used to work with Unicode characters that are
16 bits in length.
CharacterStream classes are divided into two types for this purpose:
(a). Reader classes
(b). Writer classes.
Character streams in Java, like Byte Streams, have a three-phase mechanism, as explained above.
There are numerous character stream classes in Java, but the most common ones are-
(a). FileReader
It is used to read two bytes at a time from the source. The function Object() { [native code] } for
creating an instance of the FileReader class is as follows.
Syntax of FileReader:
FileFileWriter in = new FileWriter("path_to_file");
(b). FileWriter
It is used to write two bytes at a time to the destination. The function Object() { [native code] } for
creating an instance of the FileWriter class is as follows.
Syntax of FileWriter:
FileWriter in = new FileWriter("path_to_file");
 Reading and Writing Files in Java:
File handling is an essential aspect of programming, and Java provides numerous libraries for handling files.
In this article, we will discuss how to read and write files using Java libraries.
Java provides two core libraries for handling files:
java.io package
java.nio package
The java.io package is used for file handling in Java. It provides various classes for handling files, such as
File, FileReader, FileWriter, FileInputStream, and FileOutputStream.The java.nio package is the newer file
handling library, introduced in Java 1.4. It provides better performance and scalability than the java.io
package. It provides classes like FileChannel, ByteBuffer, and Charset.
Reading from a File
To read data from a file, you need to follow the following steps:
Create a File object that represents the file you want to read.
Create a FileReader object that reads data from the file.
Use the read() method of the FileReader object to read data from the file.
Close the FileReader object using the close() method.
Here is an example:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) throws IOException {
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello World!");
fw.close(); }
}

9|Page
In the above example, we first create a File object to represent the file “filename.txt”. Then we create
a FileWriter object to write data to the file. We then use the write() method of the FileWriter object to
write the string “Hello World!” to the file. Finally, we close the FileWriter object using the close()
method.

 Java Console Class:


The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.

Java Console class declaration

Let's see the declaration for Java.io.Console class:

public final class Console extends Object implements Flushable

Java Console class methods:

Method Description

It is used to retrieve the reader


Reader reader()
object associated with the console

String readLine() It is used to read a single line of text from the console.

String readLine(String fmt, Object... It provides a formatted prompt then reads the single line of
args) text from the console.

It is used to read password that is not being displayed on the


char[] readPassword()
console.

char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is
Object... args) not being displayed on the console.

Console format(String fmt, Object... It is used to write a formatted string to the console output
args) stream.

Console printf(String format, Object...


It is used to write a string to the console output stream.
args)

It is used to retrieve the PrintWriter object associated with the


PrintWriter writer()
console.

void flush() It is used to flushes the console.

10 | P a g e
11 | P a g e

You might also like