Java - Unit4 2023-24 (CS Major)
Java - Unit4 2023-24 (CS Major)
Multithreading in Java
1. What is Thread, Multithreading and compare with multiprocessing?
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
Multithreading in java is a process of executing multiple threads simultaneously.
However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes less
time than process. Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) Enhanced performance.
2) You can perform many operations together, so it saves time. We can achieve multitasking.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
4) Threads use a shared memory area. No need of Extra memory .
1)New: The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2)Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3)Running: The thread is in running state if the thread scheduler has selected it.
4)Waiting (Blocked):This is the state when the thread is still alive, but is currently not eligible to run.
5) Dead(Terminated) : A thread is in terminated or dead state when its run() method exits.
Method Description
It is used to return a character in ASCII form. It returns -1 at the
int read()
end of file.
void close() It is used to close the FileReader class.
Useful Methods
Modifier and Method Description
Type
It atomically creates a new, empty file named by this abstract pathname if
boolean createNewFile()
and only if a file with this name does not yet exist.
boolean
mkdir() It creates the directory named by this abstract pathname.
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
New File is created!
UNIT-4
Java Console Class
The Java Console class is be used to get input from console.
It provides methods to read texts and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally.
//Java Console Example
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine(); // reads a line from console
System.out.println("Welcome "+n);
}
}
Output
Enter your name: SCIM TANUKU
Welcome SCIM TANUKU