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

Java - Unit4 2023-24 (CS Major)

Uploaded by

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

Java - Unit4 2023-24 (CS Major)

Uploaded by

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

UNIT-4

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 .

2. Explain life cycle of a Thread?( or Explain Thread states ?)


A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java
thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

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.

3) How to create aThread in java?


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
UNIT-4
Commonly used Constructors of Thread class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
Starting a Thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
 A new thread starts(with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
1)Java Thread Example by extending Thread class
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output: thread is running...
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

2) Java Thread Example by implementing Runnable interface


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi3 m1=new Multi3();
7. Thread t1 =new Thread(m1);
8. t1.start();
9. } }
Output : thread is running…
UNIT-4
4. Explain about Thread Priority?
Thread Priority: Each thread have a priority. Priorities are represented by a number between 1 and
10. In most cases, thread scheduler schedules the threads according to their priority. But it is not
guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Example of priority of a Thread:

1. class TestMultiPriority1 extends Thread{


2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5. }
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. } }
Output: running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1


UNIT-4

Java I/O Tutorial- Streams


The java.io package contains all the classes required for input and output operations. Java I/O (Input and
Output) is used to read the input and write the output. Java uses the concept of a stream to make I/O
operation fast.
Stream
 A stream is a sequence of data.
 In Java, a stream is composed of bytes.
 It's called a stream because it is a continues to flow.
The Stream classes in io package 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.

Classification of Java Stream Classes


Byte Stream Classes
Byte streams used for convenient way for reading or writing binary (8-bit) data. Byte streams are defined by
using two class hierarchies.Those are java.io.InputStream and java.io.OutputStream. Each of these abstract
classes has several concrete subclasses of each of these.

Hierarchy of Byte Stream Classes


UNIT-4
Character Stream Classes
Character Streams are used to read from the input device and write to the output device in character oriented
form. Character streams are defined by using two class hierarchies. At the top there are two abstract
classes, Reader and Writer. Java has several concrete subclasses of each of these.

Java FileWriter Class


 Java FileWriter class is used to write character-oriented data to a file.
 Unlike FileOutputStream class, you don't need to convert string into byte array because it provides
method to write string directly.
Constructors of FileWriter class
Constructor Description
Creates a new file. It gets file
FileWriter(String file)
name in string.
Methods of FileWriter class
Method Description
void write(String text) It is used to write the string into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
UNIT-4
Java FileReader Class
 Java FileReader class is used to read data from the file.
 It is character-oriented class which is used for file handling in java.
Constructors of FileReader class
Constructor Description
It gets filename in string. It opens the
FileReader(String file) given file in read mode. If file doesn't
exist, it throws FileNotFoundException.
Methods of FileReader class

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.

Java FileWriter & FileReader Example


//example program for File Writer class and File Reader Class
import java.io.*;
class IODemo
{
public static void main(String args[])throws Exception
{
//Writing data from file

FileWriter fw=new FileWriter("one.txt");


fw.write("Welcome to SCIM");
fw.close();

//Reading data from file


FileReader fr=new FileReader("one.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.println((char)i);
}
}
}
UNIT-4
Java File Class
 The File class is an abstract representation of file and directory pathname. A pathname can be either
absolute or relative.
 The File class has several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
Constructors
Constructor Description
It creates a new File instance by converting the given
File(String pathname)
pathname string into an abstract pathname.

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.

Java File Example 1


import java.io.*;
public class FileDemo {
public static void main(String[] args) {

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

You might also like