0% found this document useful (0 votes)
60 views34 pages

Java 4 and 5th Unit Notes - 064815

The document discusses Java input and output streams. It describes the three default streams in Java - System.in for standard input, System.out for standard output, and System.err for standard error output. It also discusses different types of streams like input streams, output streams, byte streams, and character streams. Finally, it provides examples of using BufferedReader and BufferedWriter classes to read and write data to streams.

Uploaded by

Tarannum Sana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views34 pages

Java 4 and 5th Unit Notes - 064815

The document discusses Java input and output streams. It describes the three default streams in Java - System.in for standard input, System.out for standard output, and System.err for standard error output. It also discusses different types of streams like input streams, output streams, byte streams, and character streams. Finally, it provides examples of using BufferedReader and BufferedWriter classes to read and write data to streams.

Uploaded by

Tarannum Sana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Java Input Output (Remaining Part of 4th Unit)

Java I/o Package


Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters, files etc
to fully execute the I/O operations.

Before exploring various input and output streams lets look at 3 standard or default
streams that Java has to provide which are also most common in use:
1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
 print(): This method in Java is used to display a text on the console. This text is passed
as the parameter to this method in the form of String. This method prints the text on the
console and the cursor remains at the end of the text at the console. The next printing
takes place from just here.
Syntax:
System.out.print(parameter);

// Java code to illustrate print()


import java.io.*;

class Demo_print {
public static void main(String[] args)
{
// using print() all are printed in the same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
Example:
// A Java program to demonstrate working of printf() in Java

class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple"+ " integer: x = %d\n",x);

// this will print it upto 2 decimal places


System.out.printf("Formatted with"+ " precision: PI = %.2f\n",Math.PI);

float n = 5.2f;

// automatically appends zero to the rightmost part of decimal


System.out.printf( "Formatted to "+ "specific width: n = %.4f\n",n);
n = 2324435.3f;
//here number is formatted from right margin & occupies width of 20 characters
System.out.printf("Formatted to "+ "right margin: n = %20.4f\n",n);
}
}

// A Java program to demonstrate working of printf() in Java


class JavaFormatter1 {
public static void main(String args[])
{ int x = 100;
System.out.printf("Printing simple"+ " integer: x = %d\n",x);
// this will print it upto 2 decimal places
System.out.printf("Formatted with"+ " precision: PI = %.2f\n",Math.PI);
float n = 5.2f;
// automatically appends zero to the rightmost part of decimal
System.out.printf("Formatted to "+ "specific width: n = %.4f\n",n);
n = 2324435.3f;
System.out.printf("Formatted to "+ "right margin: n = %20.4f\n",n);
}}
Println(): This method in Java is also used to display a text on the console. It prints the text on
the console and the cursor moves to the start of the next line at the console. The next printing
takes place from the next line.
Syntax:
System.out.println(parameter);

// Java code to illustrate println()


import java.io.*;

class Demo_print {
public static void main(String[] args)
{
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}

 printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
Example:
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple"+ " integer: x = %d\n",x);
System.out.printf("Formatted with"+ " precision: PI = %.2f\n",Math.PI);
float n = 5.2f;
System.out.printf("Formatted to "+ "specific width: n = %.4f\n",n);
n = 2324435.3f;
System.out.printf("Formatted to "+ "right margin: n = %20.4f\n",n);
}
}

2. System.err: This is the standard error stream that is used to output all the error data that
a program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
 print()
 println()
 printf()

Types of Streams:
 Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from a source
array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as outputs into an array or file or any
output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
Depending on the types of file, Streams can be divided into two primary classes which can be
further divided into other classes:
1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes,
the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream
is used to read from the source and FileOutputStream is used to write to the destination. Here is
the list of various ByteStream Classes:
2. CharacterStream: In Java, characters are stored using Unicode conventions (Refer this
for details). Character stream automatically allows us to read/write data character by
character. Though it has many classes, the FileReader and the FileWriter are the most popular
ones. FileReader and FileWriter are character streams used to read from the source and write
to the destination respectively. Here is the list of various CharacterStream Classes:
Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be
used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.

Java BufferedReader class declaration

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

1. public class BufferedReader extends Reader

Java BufferedReader class constructors

Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream that uses the default size
for an input buffer.

BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses the specified size
size) for an input buffer.

Java BufferedReader class methods

Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int off, int It is used for reading characters into a portion of an array.
len)

String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.


void reset() It repositions the stream at a position the mark method was last called on this
input stream.

void close() It closes the input stream and releases any of the system resources associated
with the stream.

Java BufferedReader Example

// Java program to illustrate BufferedReader read() method


import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Read the stream 'demo.txt' containing text "GEEKSFORGEEKS"
FileReader fileReader = new FileReader("c:/demo.txt");
// Convert fileReader to bufferedReader
BufferedReader buffReader= new BufferedReader(fileReader);
while (buffReader.ready())
{
// Read and print characters one by one by converting into character
System.out.println("Char :"+ (char)buffReader.read());
}
}
}
Java BufferedWriter Class

Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.

Class declaration

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

1. public class BufferedWriter extends Writer

Class constructors

Constructor Description

BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the default size
for an output buffer.

BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses the specified
size) size for an output buffer.

Class methods

Method Description

void newLine() It is used to add a new line by writing a line separator.

void write(int c) It is used to write a single character.

void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.

void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream


Example of Java BufferedWriter

//Java program illustrating use of write(int arg) method

import java.io.*;

public class NewClass {

public static void main(String[] args)

//initializing FileWriter

FileWriter geek_file;

try

geek_file = new FileWriter("ABC.txt");

// Initializing BufferedWriter

BufferedWriter geekwrite = new BufferedWriter(geek_file);

System.out.println("Buffered Writer start writing :)");

// Use of write() method to write the value in 'ABC' file Printing E

geekwrite.write(69);

// Printing 1

geekwrite.write(49);

// Closing BufferWriter to end operation

geekwrite.close();

System.out.println("Written successfully");

catch (IOException except)


{

except.printStackTrace();

} } }

File handling in Java using FileWriter and FileReader


Java FileWriter and FileReader classes are used to write and read data from text files (they are
Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream
classes if you have to read and write any textual information as these are Byte stream classes.

FileWriter
FileWriter is useful to create a file writing characters into it.

 This class inherits from the OutputStream class.


 The constructors of this class assume that the default character encoding and the default
byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
 FileWriter is meant for writing streams of characters. For writing streams of raw bytes,
consider using a FileOutputStream.
 FileWriter creates the output file if it is not present already.

Constructors:

FileWriter(File file) – Constructs a FileWriter object given a File object.

FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.

FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.

FileWriter (String fileName) – constructs a FileWriter object given a file name.

Methods:

public void write (int c) throws IOException – Writes a single character.

public void write (char [] stir) throws IOException – Writes an array of characters.

public void write(String str)throws IOException – Writes a string.

public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here
off is offset from which to start writing characters and len is the number of characters to write.
public void flush() throws IOException flushes the stream

public void close() throws IOException flushes the stream first and then closes the writer.

Reading and writing take place character by character, which increases the number of I/O
operations and affects the performance of the system.BufferedWriter can be used along with
FileWriter to improve the speed of execution.

The following program depicts how to create a text file using FileWriter

import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
// attach a file to FileWriter
FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Writing successful");
//close the file
fw.close();
}
}

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file.

 This class inherited from the InputStreamReader Class.


 The constructors of this class assume that the default character encoding and the default
byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
 FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.
Constructors:

 FileReader(File file) – Creates a FileReader , given the File to read from


 FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read
from
 FileReader(String fileName) – Creates a new FileReader , given the name of the file to
read from

Methods:

 public int read () throws IOException – Reads a single character. This method will block
until a character is available, an I/O error occurs, or the end of the stream is reached.
 public int read(char[] cbuff) throws IOException – Reads characters into an array. This
method will block until some input is available, an I/O error occurs, or the end of the stream
is reached.
 public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters
into a portion of an array. This method will block until some input is available, an I/O error
occurs, or the end of the stream is reached.

Parameters:

cbuf – Destination buffer

off – Offset at which to start storing characters

len – Maximum number of characters to read

public void close() throws IOException closes the reader.

public long skip(long n) throws IOException –Skips characters. This method will block until some
characters are available, an I/O error occurs, or the end of the stream is reached.

Parameters:

n – The number of characters to skip


The following program depicts how to read from the ‘text’ file using FileReader

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;

// check if File exists or not


FileReader fr=null;
try
{
fr = new FileReader("text");
}
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}

// read from FileReader till the end of file


while ((ch=fr.read())!=-1)
System.out.print((char)ch);

// close the file


fr.close();
}
}

PrintWriter class in Java

This class gives Prints formatted representations of objects to a text-output stream. It implements
all of the print methods found in PrintStream. It does not contain methods for writing raw bytes,
for which a program should use unencoded byte streams.

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of
the println, printf, or format methods is invoked, rather than whenever a newline character
happens to be output. These methods use the platform’s own notion of line separator rather than
the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The
client may inquire as to whether any errors have occurred by invoking checkError().

Constructor and Description


 PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with the
specified file.
 PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line
flushing, with the specified file and charset.
 PrintWriter(OutputStream out) : Creates a new PrintWriter, without automatic line
flushing, from an existing OutputStream.
 PrintWriter(OutputStream out, boolean autoFlush) : Creates a new PrintWriter from an
existing OutputStream.
 PrintWriter(String fileName) : Creates a new PrintWriter, without automatic line flushing,
with the specified file name.
 PrintWriter(String fileName, String csn) : Creates a new PrintWriter, without automatic
line flushing, with the specified file name and charset.
 PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing.
 PrintWriter(Writer out, boolean autoFlush) : Creates a new PrintWriter.
Files in Java

A file is aabstract data type. A named location used to store related information is known as a File.

There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.

Stream

A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.

Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a
process in which an input is provided and executed with the byte data.

Character Stream

Character Stream is mainly involved with character data. A file handling process with a character
stream is a process in which an input is provided and executed with the character data.

To get more knowledge about the stream, click here.

Java File Class Methods

S.No. Method Return Description


Type

1. canRead() Boolean The canRead() method is used to check whether we can read the
data of the file or not.

2. createNewFile() Boolean The createNewFile() method is used to create a new empty file.

3. canWrite() Boolean The canWrite() method is used to check whether we can write the
data into the file or not.
4. exists() Boolean The exists() method is used to check whether the specified file is
present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the file name.

7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute pathname
of the file.

8. length() Long The length() method is used to get the size of the file in bytes.

9. list() String[] The list() method is used to get an array of the files available in the
directory.

10. mkdir() Boolean The mkdir() method is used for creating a new directory.

File Operations
We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File

Create a File

Create a File operation is performed to create a new file. We use the createNewFile() method of
file. The createNewFile() method returns true when it successfully creates a new file and returns
false when the file already exists.
Get File Information

The operation is performed to get the file information. We use several methods to get the
information about the file like name, absolute path, is readable, is writable and length.

Write to a File

The next operation which we can perform on a file is "writing into a file". In order to write data
into a file, we will use the FileWriter class and its write() method together. We need to close the
stream using the close() method to retrieve the allocated resources.

Read from a File

The next operation which we can perform on a file is "read from a file". In order to write data
into a file, we will use the Scanner class. Here, we need to close the stream using
the close() method. We will create an instance of the Scanner class and use
the hasNextLine() method nextLine() method to get data from the file.

Delete a File

The next operation which we can perform on a file is "deleting a file". In order to delete a file,
we will use the delete() method of the file. We don't need to close the stream using
the close() method because for deleting a file, we neither use the FileWriter class nor the Scanner
class.

Serialization and Deserialization in Java

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is


mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into
an object. The serialization and deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for
deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by
default.

Let's see the example given below:

Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream. The main class implementation of is showed in the next code.

Example of Java Serialization

In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object. We are saving the state of the object in the file named f.txt.

import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}

Example of Java Deserialization

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.

Depersist.java

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Unit 5 Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

Java Thread Methods


S.N. Modifier and Method Description
Type

1) Void start() It is used to start the execution of the thread.

2) Void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread() It returns a reference to the currently executing thread objec

5) Void join() It waits for a thread to die.

6) Int getPriority() It returns the priority of the thread.

7) Void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) Void setName() It changes the name of the thread.

10) Long getId() It returns the id of the thread.

11) Boolean isAlive() It tests if the thread is alive.

12) Void suspend() It is used to suspend the thread.

13) Void resume() It is used to resume the suspended thread.

14) Void stop() It is used to stop the thread.

15) Void destroy() It is used to destroy the thread group and all of its subgroup
How to create a thread 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.

Commonly used Constructors of Thread class:

 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

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.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
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

FileName: Multi.java

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. }

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }

If you are not extending the Thread class, your class object would not be treated as a thread object.
So you need to explicitly create the Thread class object. We are passing the object of your class
that implements Runnable so that your class run() method may execute.

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined above.

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }
4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }
24. }
Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent.

REFER THREAD PRORITIES LAB PROGRAM FOR EXAMPLE

Thread isAlive() method


The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when
the start() method of thread class has been called and the thread is not yet dead. This method
returns true if the thread is still running and not finished.

Syntax
1. public final boolean isAlive()

Return
This method will return true if the thread is alive otherwise returns false.

Example
1. public class JavaIsAliveExp extends Thread
2. {
3. public void run()
4. {
5. try
6. {
7. Thread.sleep(300);
8. System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
9. }
10. catch (InterruptedException ie) {
11. }
12. }
13. public static void main(String[] args)
14. {
15. JavaIsAliveExp t1 = new JavaIsAliveExp();
16. System.out.println("before starting thread isAlive: "+t1.isAlive());
17. t1.start();
18. System.out.println("after starting thread isAlive: "+t1.isAlive());
19. }
20. }
Java join() method

The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait
until the other thread to finish its execution. Suppose th be the object the class Thread whose thread
is doing its execution currently, then the th.join(); statement ensures that th is finished before the
program does the execution of the next statement. When there are more than one thread invoking
the join() method, then it leads to overloading on the join() method that permits the developer or
programmer to mention the waiting period.

import java.io.*;
import java.util.*;

public class Threadjoiningmethod extends Thread{


public void run(){
for(int i=1;i<=4;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
Threadjoiningmethod th1=new Threadjoiningmethod ();
Threadjoiningmethod th2=new Threadjoiningmethod ();
Threadjoiningmethod th3=new Threadjoiningmethod ();
th1.start();
try{
th1.join();
}
catch(Exception e){
System.out.println(e);
}

th2.start();
th3.start();
}
}
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.

When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues. For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one thread is opening the
same file at the same time another thread might be closing the same file.

So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Java Synchronized Method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

1. class Table {
2. synchronized void printTable(int n){//synchronized method
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. public class TestSynchronization2{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }

Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in


its critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:

 wait()
 notify()
 notifyAll()
1) wait() method

The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of time
has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) notify() method

The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs
at the discretion of the implementation.

Syntax: public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax: public final void notifyAll()

Difference between wait and sleep?

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Example of Inter Thread Communication in Java

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}

Java Thread suspend() method


The suspend() method of thread class puts the thread from running to waiting state. This method
is used if you want to stop the thread execution and start it again when a certain event occurs. This
method allows a thread to temporarily cease execution. The suspended thread can be resumed
using the resume() method.
Syntax
1. public final void suspend()

Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }

Thread resume() method


The resume() method of thread class is only used with suspend() method. This method is used to
resume a thread which was suspended using suspend() method. This method allows the suspended
thread to start again.
Syntax
1. public final void resume()

Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. t2.suspend(); // suspend t2 thread
26. // call run() method
27. t3.start();
28. t2.resume(); // resume t2 thread
29. }
30. }

Java Thread stop() method


The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.
Syntax
1. public final void stop()

Example
1. public class JavaStopExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaStopExp t1=new JavaStopExp ();
20. JavaStopExp t2=new JavaStopExp ();
21. JavaStopExp t3=new JavaStopExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // stop t3 thread
26. t3.stop();
27. System.out.println("Thread t3 is stopped");
28. }
29. }

You might also like