Vous êtes sur la page 1sur 111

Department of Computer Science and Engineering (CSE)

JAVA IO

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

File
Although most of the classes defined by java.io
operate on streams, the File class does not. It
deals directly with files and the file system.
A File object is used to obtain the information
associated with a disk file, such as the
permissions, time, date, and directory path.
Creating object:
File f1=new File(ggg.txt);

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Sample Program

import java.io.*;
class FileExample{
public static void main(String args[]){
File obj=new File(d:/Java/input.txt);
System.out.println(obj.exists());
System.out.println(obj.getName());
System.out.println(obj.length());
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Sample Program (Creating new File)

import java.io.*;
class FileExample{
public static void main(String args[]){
File obj=new File(d:/Java/input.txt);
Obj.createNewFile();
System.out.println(obj.exists());
System.out.println(obj.getName());
System.out.println(obj.length());
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
File(contd.)
File defines many methods that obtain the
standard properties of a File object. For Ex,
Creating object- File file1 = new File("input.txt");
f1.getName(); returns name of file
f1.getPath(); returns full path
f1.getParent(); get name of parent directory
f1.exists(); exists or not?
f1.canWrite(); is writable?
f1.canRead(); is readable?
f1.lastModified(); File last modified
f1.length(); returns size in bytes

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

IO Stream
Java performs I/O throughStreams. In general, a stream means
continuous flow of data.
AnI/O Streamrepresents an input source or an output destination.
A stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs.
Streams are objects that represent sources and destinations of
data. A stream in Java is an ordered sequence of bytes of
undetermined length. Streams are ordered and in sequence so that
the java virtual machine can understand and work upon the stream.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Concept of Streams
In file processing, input refers to the flow of data into a
program and output means the flow of data out of a program.
Input to a program may come from the keyboard, the mouse,
the memory, the disk, a network or another program.
Similarly, output from a program may go to the screen, the
printer, the memory, the disk, a network, or another program.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Concept of Streams(contd.)
A stream is a path along which data flows. It has a
source(of data) and a destination(for that data).

Java Streams are classified into two basic types,


namely, input stream and output stream.
Input Stream: extracts(reads) data from the source (file)
and sends it to the program.
Output Stream: takes data from the program and
sends(writes) it to the destination (file).

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

JAVA STREAMS
Java defines two types of streams. They are,
Byte Stream :It provides a convenient means
for handling input and output of byte.
Character Stream :It provides a convenient
means for handling input and output of
characters. Character stream uses Unicode and
therefore can be internationalized.
(Internationalization is a mechanism to create
such an application that can be adapted to
different languages and regions.)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Byte stream is defined by using two abstract class


at the top of hierarchy, they are InputStream and
OutputStream.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Character stream is also defined by using two
abstract class at the top of hierarchy, they are
Reader and Writer.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Stream classes
Byte Stream Character Stream
InputStream Abstract Reader Abstract class
class Writer Abstract class
OutputStream Abstract
class
FileInputStream FileReader
FileOutputStream FileWriter
ByteArrayInputStream CharArrayReader
ByteArrayOutputStream CharArrayWriter
FilterInputStream BufferedReader
FilterOutputStream BufferedWriter
BufferedInputStream InputStreamReader
BufferedOutputStream OutputStreamReader
DataInputStream PrintWriter
DataOutputStream
PipedInputStream
PipedOutputStream
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Stream Classes(contd.)

Byte streams and


character streams classes
contain specialized
classes to deal with input
and output operations
independently on various
types of devices.
We can also cross-group
the streams based on the
type of source or
destination they read from
or write to. The source or
destination may be
memory, file or a pipe.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Input Stream Classes
Byte Stream
Classes- Input
Stream Classes
Java provides two kinds of
byte stream classes: input
stream classes and output
stream classes.
The super class InputStream
is an abstract class and
therefore, we cannot create
instances of this class.
Rather, we must use the
subclasses that inherit from
this class.
The Input stream class
defines methods for
performing input functions
such as:
Reading bytes
Closing streams
Marking positions in streams
Skipping ahead in a stream
Finding the number of bytes in a
stream.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

InputStream Class methods

int read()
This method reads a byte of data from this input stream.
int read(byte[] b)
This method reads up tob.lengthbytes of data from this input stream into an
array of bytes.
int read(byte[] b, int n, int m)
This method reads m bytes into b starting from nth byte.
int available()
This method gives number of bytes available in the input.
long skip(long n)
This method skips over and discards n bytes of data from the input stream.
reset()
Goes back to the beginning of the stream.
void mark(int numBytes)
places a mark at the current point in the input stream that will remain valid
until numBytes are read.
void close()
This method closes this file input stream and releases any system resources
associated with the stream.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Byte Stream Output Stream Classes

Classes- Output
Stream Classes
The super class
OutputStream is an
abstract class and
therefore, we cannot
create instances of this
class. Rather, we must
use the subclasses that
inherit from this class.
The Output stream class
defines methods for
performing output
functions such as:
Writing bytes
Closing streams
Flushing Streams

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

OutputStream Class methods

int write(int b)
This method writes a byte of data to the output stream.
int write(byte[] b)
Writes all bytes in the array b to the output stream.
int write(byte[] b, int n, int m)
This method writes m bytes from array b starting from
nth byte.
void close()
This method closes this file input stream and releases
any system resources associated with the stream.
Flush()
Flushes the output stream.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileInputStream
TheFileInputStreamclass makes it possible to read the
contents of a file as a stream of bytes.
TheFileInputStreamclass is a subclass ofInputStream.
The FileInputStream class creates an InputStream that
you can use to read bytes from a file.
Java FileInputStream class obtains input bytes from a file.
Constructors are shown below:

FileInputStream(File file)
This creates a FileInputStream by opening a connection to
an actual file, the file named by the File objectfilein the file
system.
FileInputStream(String name)
This creates a FileInputStream by opening a connection to
an actual file, the file named by the path namenamein the
file system.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileInputStream(contd.)

Reading from file using read(): This method reads a b


from the input stream.

FileInputStream fin=new FileInputStream("abc.txt");

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

import java.io.*;
class FileRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.print(e);}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileInputStream(contd.)
Reading from file using read(byte[] b):
Thejava.io.InputStream.read(byte[] b)method read
number of bytes from the input stream to the buffer arra
The bytes read is returned as integer.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

import java.io.*;
class FileRead{
public static void main(String args[]){
int i=0;
char c='\0';
byte[] buffer=new byte[9];
try{
FileInputStream fin=new
FileInputStream("abc.txt");
fin.read(buffer);
for(byte b:buffer){
c=(char)b;
System.out.println(c);}
fin.close(); }
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileInputStream(contd.)

Reading from file using read(byte[] b, int off, int l


reads upto len bytes of data from the input stream into
of bytes.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
import java.io.*;
class FileRead{
public static void main(String args[]){
int i=0;char c='\0';
byte[] buffer=new byte[9];
try{
FileInputStream fin=new
FileInputStream("abc.txt");
fin.read(buffer,6,3);
for(byte b:buffer){
c=(char)b;
System.out.print(c);}
fin.close(); }
catch(Exception e){System.out.print(e);} }}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Reading from file using available() and
read():
import java.io.*;
class FileRead{
public static void
main(String args[]){
try{
FileInputStream fin=new
FileInputStream("abc.txt");
int i=0;
while(fin.available()>0) {

i=fin.read();
System.out.print((char)i);
}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Using skip() method


import java.io.*;
class FileRead{
public static void main(String
args[]){
try{
FileInputStream fin=new
FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1) {
fin.skip(1);
System.out.print((char)i); }
fin.close();
}catch(Exception e)
{System.out.print(e);}
}
} University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileOutputStream
FileOutputStream class is an output stream for writing
data to a File.
Constructors:
FileOutputStream(File file)
This creates a file output stream to write to the file
represented by the specifiedFileobject.
FileOutputStream(File file, boolean append)
This creates a file output stream to write to the file
represented by the specifiedFileobject.
FileOutputStream(String name)
This creates an output file stream to write to the file with the
specified name.
FileOutputStream(String name, boolean append)
This creates an output file stream to write to the file with the
specified name.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileOutputStream(contd.)
Writing into a file using write(intb): This method
writes a byte of data to the output stream
import java.io.*;
class FileWrite{
public static void main(String args[])
{

try
{
FileOutputStream fout=new FileOutputStream("abc.txt");
fout.write(65);
fout.close();
}
catch(Exception e){System.out.print(e);}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileOutputStream(contd.)
Writing into a file using write(byte[]b): Writes all
bytes in the array b to the output stream.
import java.io.*;
class FileWrite{
public static void main(String args[])
{
String s="java programming";
try
{
FileOutputStream fout=new FileOutputStream("abc.txt");
byte[] contentinbytes = s.getBytes();getBytes():Encodes this String
fout.write(contentinbytes); into a sequence of bytes.
fout.close();
}
catch(Exception e){System.out.print(e);}
}
}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileOutputStream(contd.)
Writing into a file using write(byte[]b, int n, int
m): This method writes m(length) bytes from array b
importstarting from nth(offset) byte.
java.io.*;
class FileWrite{
public static void main(String args[])
{
String s="java programming";
try
{
FileOutputStream fout=new FileOutputStream("abc.txt");
byte[] contentinbytes = s.getBytes();
fout.write(contentinbytes, 2,3);
fout.close();
}
catch(Exception e){System.out.print(e);}
}
}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileOutputStream(contd.)
flush(): If you want to make sure that all written
data is written to disk without having to close
theFileOutputStream,you can call
itsflush()method. Callingflush()will make sure
that all data which has been written to
theFileOutputStreamso far, is fully written to
disk too.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Copy contents of one file into another


import java.io.*;
public class CopyFile {
public static void main(String
args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new
FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}finally {
in.close();
} out.close(); }}}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Copy contents of one file into another

import java.io.*;
public class CopyFile {
public static void main(String args[]) throws
IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
File file1 = new File("input.txt");
in=new FileInputStream(file1);
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
in.close();
out.close(); University
} }} Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

ByteArrayInputStream &
ByteArrayOutputStream

The ByteArrayInputStream class allows a buffer in


the memory to be used as an InputStream. The input
source is a byte array.
ByteArrayInputStream(byte [] a)This constructor
accepts a byte array as parameter.
ByteArrayInputStream(byte [] a, int off, int len)This
constructor takes an array of bytes, and two integer
values, whereoffis the first byte to be read andlenis
the number of bytes to be read.
The ByteArrayOutputStream class stream creates a
buffer in memory and all the data sent to the stream
is stored in the buffer.
ByteArrayOutputStream()This constructor creates a
ByteArrayOutputStream having buffer of 32 bytes.
ByteArrayOutputStream(int a)This constructor creates
a ByteArrayOutputStream having buffer of the given size.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

import java.io.ByteArrayInputStream; import java.io.*;


public class ByteArrayInputStreamExample { public class ByteArrayOutputStreamExample {
public static void main(String[] args) { public static void main(String args[])throws
IOException {
String str = "ByteArrayInputStream Example!";
ByteArrayOutputStream bOutput = new
//get bytes from string using getBytes method ByteArrayOutputStream();
byte[] bytes = str.getBytes(); while( bOutput.size()!= 10 )
{
//create ByteArrayInputStream object // Gets the inputs from the user
ByteArrayInputStream bai = new bOutput.write(System.in.read());
ByteArrayInputStream(bytes); }
byte byteArray [] = bOutput.toByteArray();
int ch; System.out.println("Print the content");
for(byte b: byteArray)
//read bytes from ByteArrayInputStream using {
read method //printing the characters
while((ch = bai.read()) != -1) System.out.print((char)b);
{ }
System.out.print((char)ch);
} }
}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Using reset() and mark() with
import java.io.*;
ByteArrayInputStream
public class ByteArrayInputStreamExample {

public static void main(String args[])throws


IOException {

String str = "ByteArrayInputStream Example!";

//get bytes from string using getBytes method


byte[] byteArray = str.getBytes();

//create ByteArrayInputStream object


ByteArrayInputStream bai = new
ByteArrayInputStream(byteArray);

System.out.print((char)bai.read());
System.out.print((char)bai.read());
System.out.print((char)bai.read());
System.out.print((char)bai.read());
bai.mark(0);
System.out.print((char)bai.read());
System.out.print((char)bai.read());
bai.reset();
System.out.print((char)bai.read());
System.out.print((char)bai.read());
System.out.print((char)bai.read());
System.out.print((char)bai.read());

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FilterStream: FilterInputStream,
FilterOutputStream
FilterOutputStream: FilterOutputStream
implements OutputStream class and overrides its
methods. Further, FilterOutputStream has
different sub classes to provide different type of
functionality. Subclasses such as
BufferedOutputStream, DataOutputStream,
ZipOutputStream,etc.
FilterInputStream: FilterInputStream implements
InputStream. Further, FilterInputStream has
different sub classes for different purpose as
BufferedInputStream, DataInputstream,
ZipInputStream, etc

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

BufferedOutputStream,
BufferedInputStream
The BufferedOutputStream class provides buffering to your
output streams. Buffering can speed up IO . Rather than writing
one byte at a time to the network or disk, you write a larger
block at a time. This is typically much faster, especially for disk
access and larger data amounts. Default size of buffer is 8192
bytes.
The BufferedInputStream class provides buffering to your input
streams. Buffering can speed up IO. Rather than read one byte
at a time, the BufferedInputStream reads a larger block at a
time into the internal buffer. When you read a byte from the
BufferedInputStream you are therefore reading it from its
internal buffer. When the buffer is fully read, the
BufferedInputStream reads another larger block of data into the
buffer. This is typically much faster than reading a single byte at
a time from an InputStream, especially for disk access and
larger data amounts.
Both the classes support mark() and reset().

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

import java.io.*; BufferedInputStream


public class BufferedInputStreamExample
{
public static void main(String ar[]) throws Exception
{
FileInputStream fin=new FileInputStream("abc.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
new String
byte[] contents=new byte[1024];
(contents,0,bytesRead);
int bytesRead=0;
contents: is byte array to print
String fileContents;
0:specifies the index from
while((bytesRead=bin.read(contents))!=-1)
which to start
{
copying.
System.out.println(bytesRead);
bytesRead: specifies number of
fileContents=new String (contents,0,bytesRead);
characters to
System.out.println(fileContents); //prints the
print.
contents of file
}

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

If I am not printing filecontents,


then output will be this
It means it reads 1024 bytes
each time and prints 1024
bytes at one go.
In the last, 167 bytes were
remaining, so it will print those
as well and then -1 is returned
which makes the condition
false and out of the loop. Institute
University of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

import java.io.*; BufferedOutputStream


public class BufferedOutputStreamExample
{
public static void main(String ar[]) throws Exception
{
FileOutputStream fout=new FileOutputStream("abc.txt");
BufferedOutputStream bout=new
BufferedOutputStream(fout);

try
{
String s="Java Programming";
bout.write(s.getBytes());
}
finally
{
bout.close();
}

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

DataInputStream & DataOutputStream


DataInputStreamandDataOutputStreamare subclasses
ofFilterInputStreamandFilterOutputStream. These
streams' extra functionality is that they can read or write
integers, doubles and lines at a time, instead of byte by
byte. This increases the performance to some extent; instead
of reading and writingbyte by bytewith FileInputStream and
FileOutputStream.
Performance Advantage with DataInputStream and
DataOutputStream

These streams improve the speed of copying. To achieve


performance, theDataInputStreamclass comes with some
special methods
likereadInt(),readDouble()andreadLine()etc. Similarly,
theDataOutputStreamcomes with methods
likewriteInt(),writeDouble()andwriteBytes()etc. These
methods can read and write an integer, a double and a line
as a whole at a time instead of byte by byte.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

DataInputStream & DataOutputStream


import java.io.*;
Example
public class DataInputOutputStreamExample {
public static void main(String[] args) throws
IOException {
String strFile = "abc.txt";
FileOutputStream fos = new
FileOutputStream(strFile);
DataOutputStream dos = new
DataOutputStream(fos);
int num = 100;
dos.writeInt(num);
dos.close();

FileInputStream fin = new


DataInputStream:
FileInputStream(strFile);
DataInputStream dis = new java.io.DataInputStream
DataInputStream(fin); reads primitive data from a
int i=dis.readInt(); file through an input
System.out.println(i); stream.
DataOutputStream:
} java.io.DataInputStream
}
University Institute of writes
Engineering
primitive(UIE)
data to a
Department of Computer Science and Engineering (CSE)

PrintStream
TheJava.io.PrintStreamclass adds functionality to another
output stream, the ability to print representations of various
data values conveniently. The JavaPrintStreamclass
(java.io.PrintStream)
void print(boolean b) enables you to write formatted data to an
import java.io.*;
underlyingOutputStream.
void print(char c) public class PrintStreamExample {
void print(double d)
void print(float f) public static void main(String[] args) {
void print(int i) int x = 5;
void print(long l)
// create printstream object
void print(String s)
PrintStream ps = new
void println() PrintStream(System.out);
void println(boolean x)
void println(char x) // print integer
void println(double x) ps.println(x);
void println(float x) ps.println(100);
void println(int x) ps.print(12.56);
}
void println(long x)
}
void println(String x)
and many more..
University Institute of Engineering (UIE)
PipedInputStream &
Department of Computer Science and Engineering (CSE)

PipedOutputStream
PipedInputStream and PipedOutputStream : Pipes are
used to channel the output from one program (or
thread) into the input of another. Why is this useful?
Consider a class that implements various string
manipulation utilities such as sorting and reversing text.
It would be nice if the output of one of these methods
could be used as the input for another so that you could
string a series of method calls together to perform some
higher-order function. For example, you could reverse
each word in a list, sort the words, and then reverse
each word again to create a list of rhyming words.
Without pipe streams, the program would have to store
the results somewhere (such as in a file or in memory)
between each step, as shown here:
With pipe
streams, the
output from one
method could be
piped into the
University Institute next,
of Engineering
as shown (UIE)
Department of Computer Science and Engineering (CSE)
import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
PipedInputStream and
final PipedInputStream pin=new PipedInputStream();
PipedOutputStream
pout.connect(pin);//connecting the streams
//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{ The PipedInputStream
pout.write(i); //writing into the PipedOutputStream
Thread.sleep(1000); and PipedOutputStream
}catch(Exception e){}
} classes can be used to
}
}; read and write data
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
simultaneously. Both
try{
for(int i=65;i<=90;i++)
streams are connected
with each other using
System.out.println(pin.read()); //reading from the PipedInputStream
}catch(Exception e){}
}
};
the connect() method of
//starting both threads
t1.start();
the PipedOutputStream
t2.start();
}}
class.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Serialization and De-Serialization


Java provides a mechanism, called object serialization where an
object can be represented as a sequence of bytes that includes the
objects data as well as information about the objects type and the
types of data stored in the object.
After a serialized object has been written into a file, it can be read
from the file and deserialized that is, the type information and bytes
that represent the object and its data can be used to recreate the
object in memory.
Entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different
platform.
For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it
must be marked transient.
ObjectOutputStream class is used to serialize an object. When the
program is done executing, a file named Employee.ser is
created(standard convention).
ObjectInputStream class is used to deserialize the object.

University Institute of Engineering (UIE)


import java.io.*; Department of Computer Science and Engineering (CSE)
class Employee implements Serializable
{
Serialization
String name, address, empid;
int SSN;
(without transient)
}
public class Object_Serialization
{
public static void main(String arg[])
{
Employee e=new Employee();
e.name="Arvind Kaur";
e.address="Mohali, Punjab";
e.SSN=1234;
e.empid="E333";
try
{
FileOutputStream fout=new
FileOutputStream("Employee.ser");
ObjectOutputStream obout=new ObjectOutputStream(fout);
obout.writeObject(e);
obout.close();
fout.close();
System.out.println("Serialized data is saved in
Employee.ser");
}
catch(IOException i)
{
System.out.println(i);
} Employee.ser will be created in the
} University Institute of Engineering (UIE)
import java.io.*;
Department of Computer Science and Engineering (CSE)
public class Object_DeSerialization
{
De-Serialization
public static void main(String arg[]) (without transient)
{
Employee e=null;

try
{
FileInputStream fin=new
FileInputStream("Employee.ser");
ObjectInputStream obin=new
ObjectInputStream(fin);
e=(Employee)obin.readObject();

fin.close();
obin.close();
System.out.println("Name:"+e.name+"\nAddress: "+e.address+"\nSSN:
"+e.SSN+"\nempid:"+e.empid);
}
catch(IOException i)
{
System.out.println(i);
}
catch(ClassNotFoundException i)//readObject() may throw
exception which

should be declared.
{
System.out.println(i);
University Institute of Engineering (UIE)
import java.io.*; Department of Computer Science and Engineering (CSE)
class Employee implements Serializable
{
Serialization
String name, address;
transient String empid;
(with transient)
int SSN;
}
public class Object_Serialization
{
public static void main(String arg[])
{
Employee e=new Employee();
e.name="Arvind Kaur";
e.address="Mohali, Punjab";
e.SSN=1234;
e.empid="E333";
try
{
FileOutputStream fout=new
FileOutputStream("Employee.ser");
ObjectOutputStream obout=new ObjectOutputStream(fout);
obout.writeObject(e);
obout.close();
fout.close();
System.out.println("Serialized data is saved in
Employee.ser");
}
catch(IOException i)
{
System.out.println(i); Employee.ser will be created in the
University
} Institute of Engineering (UIE)
import java.io.*;
Department of Computer Science and Engineering (CSE)
public class Object_DeSerialization
{
De-Serialization
public static void main(String arg[]) (with transient)
{
Employee e=null;

try
{
FileInputStream fin=new
FileInputStream("Employee.ser");
ObjectInputStream obin=new
ObjectInputStream(fin);
e=(Employee)obin.readObject(); The
value of SSN was E333
When the object was serializ
fin.close();
obin.close(); But because the field is tran
this value was not sent to th
System.out.println("Name:"+e.name+"\nAddress: "+e.address+"\nSSN:
"+e.SSN+"\nempid:"+e.empid); output stream. Empid is null
}
as shown in the output.
catch(IOException i)
{
System.out.println(i);
}
catch(ClassNotFoundException i)//readObject() may throw
exception which should be declared.
{
System.out.println(i);
}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Character Stream Classes

Character streams can be


used to read and write
characters.
There are 2 kinds of
character stream classes:
Reader stream class
Writer Stream class
Reader Stream classes:
Reader stream classes are
designed to read character
from the files.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Character Stream Class


Writer Stream classes:
Writer stream classes are
designed to write
characters in the file.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Reader class Methods


abstract void close()
This method closes the stream and releases any system resources associated
with it.
void mark(int readAheadLimit)
This method marks the present position in the stream.
boolean markSupported()
This method tells whether this stream supports the mark() operation.
int read()
This method reads a single character.
int read(char[] cbuf)
This method reads characters into an array.
abstract int read(char[] cbuf, int off, int len)
This method reads characters into a portion of an array.
int read(CharBuffer target)
This method attemptsto readcharacters into the specified character buffer.
boolean ready()
This method tells whether this stream is ready to beread.
void reset()
This method resets the stream.
long skip(long n)
This method skips characters.
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileReader class
FileReader is used for reading streams of
characters.
This class has several constructors to create
required objects. Below given are the list of
constructors provided by the FileReader class.
FileReader(File file)This constructor creates a new
FileReader, given the File to read from.
FileReader(String fileName)This constructor
creates a new FileReader, given the name of the file to
read from.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileReader Methods
Reading from file using read(): This method reads a s
import java.io.*;
class FileRead{
public static void main(String args[]){
try{
FileReader fin=new FileReader("abc.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.print(e);}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileReader Methods(contd.)
Reading from file using read(char[] cbuf) : This met
characters into an array.
import java.io.*;
class FileRead {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("abc.txt");

// create a char array to read chars into


char cbuf[] = new char[100];

// read characters into an array.


reader.read(cbuf);

System.out.println(cbuf);
reader.close();

} catch (IOException ex) {


ex.printStackTrace();
}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileReader Methods(contd.)

Reading from file using read(char[] cbuf, int offset


method reads characters into a portion of an array.
import java.io.*;
class FileRead {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("abc.txt");

// create a char array to read chars into


char cbuf[] = new char[100];

// read characters into an array.


reader.read(cbuf,4,3);

System.out.println(cbuf);
reader.close();

} catch (IOException ex) {


ex.printStackTrace();
}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Writer class Methods


append(charc)
Appends the specified character to this writer.
append(CharSequencecsq)
Appends the specified character sequence to this writer.
append(CharSequencecsq, intstart, intend)
Appends a subsequence of the specified character sequence to this writer.
abstract void close()
Closes the stream, flushing it first.
abstract void flush()
Flushes the stream.
void write(char[]cbuf)
Writes an array of characters.
abstract void write(char[]cbuf, intoff, intlen)
Writes a portion of an array of characters.
void write(intc)
Writes a single character.
void write(Stringstr)
Writes a string.
void write(Stringstr, intoff, intlen)
Writes a portion of a string.
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileWriter Class
The class is used for writing streams of characters.
This class has several constructors to create required
objects. Below given is the list of them:
FileWriter(File file)
This constructor creates a FileWriter object given a File object.
FileWriter(File file, boolean append)
This constructor creates a FileWriter object given a File object.
with a boolean indicating whether or not to append the data
written.
FileWriter(String fileName)
This constructor creates a FileWriter object, given a file name.
FileWriter(String fileName, boolean append)
This constructor creates a FileWriter object given a file name
with a boolean indicating whether or not to append the data
written.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Writing into a file using write(intb): This method
writes a byte of data to the output stream
import java.io.*;
class FileWrite{
public static void main(String args[])
{

try
{
FileWriter fout=new FileWriter("abc.txt");
fout.write(65);
fout.close();
}
catch(Exception e){System.out.print(e);}
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Writing into a file using void write(char[] buf):
Writes an array of characters.
import java.io.*;

public class FileWrite {


public static void main(String[] args) throws IOException
{
FileWriter writer = new FileWriter("abc.txt");
char[] buffer = {'A', 'B', 'C', '\n'};
writer.write(buffer);
writer.close();
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Writing into a file using abstract void write(char[]
cbuf, int off, int len): Writes a portion of an array
of characters.

import java.io.*;

public class FileWrite{


public static void main(String[] args) throws IOException
{
FileWriter writer = new FileWriter("abc.txt");
char[] buffer = {'1', '2', '3', 'X', 'Y', 'Z', '\n'};
writer.write(buffer, 3, 4);
writer.close();
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Writing into a file using void write(String str):
Writes a string.
import java.io.*;
class FileWrite{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("Java Programming");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Writing into a file using void write(String atr,int
off, int len):Writes a portion of a string.

import java.io.*;
class FileWrite{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("Java Programming",3,4);
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

FileWriter Methods
Appending to a file using
append(CharSequence csq):
Appends the specified character sequence to this
writer.
import java.io.*;
class FileWrite {
public static void main(String[] args) {
try {
FileWriter reader = new FileWriter("abc.txt",true);

reader.append("Appended string");
reader.close();

} catch (IOException ex) {


ex.printStackTrace();
}
}
}
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

FileWriter Methods
Appending to a file using append(CharSequence
csq, int start, int end): appends a subsequence of the specified
character sequence to this writer.
csq The character sequence to append.
start The index of the first character in the subsequence.
end The index of the character following the last character in the
subsequence

import java.io.*;
class FileWrite {
public static void main(String[] args) {
try {
FileWriter reader = new FileWriter("abc.txt",true);

reader.append("Appended string",4,7);
reader.close();

} catch (IOException ex) {


ex.printStackTrace();
}
}
} University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

BufferedReader & BufferedWriter


The JavaBufferedReaderclass
(java.io.BufferedReader) provides buffering to
yourReaderinstances. Buffering can speed up IO
quite a bit. Rather than read one character at a time
from the network or disk, theBufferedReaderreads
a larger block at a time. This is typically much faster,
especially for disk access and larger data amounts.
The JavaBufferedReaderis similar to
theBufferedInputStream but they are not exactly
the same. The main difference
betweenBufferedReaderandBufferedInputStreamis
thatBufferedReaderreads characters (text),
whereas theBufferedInputStreamreads raw bytes.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

BufferedReader & BufferedWriter


import java.io.*; import java.io.*;
public class BufferedReaderExample public class BufferedWriterExample
{ {
public static void main(String ar[]) throws public static void main(String ar[]) throws
Exception Exception
{ {
FileReader fr=new FileReader("abc.txt"); FileWriter fw=new FileWriter("abc.txt");
BufferedReader br=new BufferedReader(fr); BufferedWriter bw=new BufferedWriter(fw);
String s = new String(); try
while ((s = br.readLine()) != null) {
{ String s="Java Programming";
System.out.println(s); bw.write(s);
} }
} finally
} {
bw.close();
}

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
import java.io.*;
StringReader &
public class StringReaderDemo { StringWriter
public static void main(String[] args) StringWriter:
{ The JavaStringWriterclas
(java.io.StringWriter) enables you to obta
String s = "Java Programming"; characters written to a Writer as aString
StringReader sr = new TheStringWriteris useful if you have a
StringReader(s);
component that only can write data to a
StringWriter sw = new StringWriter();
sw.write("This is a text");
but you need that data as a String.
System.out.println(sw);
try { StringReader: The JavaStringReadercl
// read chars enables you to turn an ordinaryStringin
Reader.This is useful if you have data as
for (int i = 0; i < s.length(); i++) {
char c = (char) sr.read(); but need to pass that String to a compon
System.out.print("" + c); only accepts aReader.
}

// close the stream


sr.close();

} catch (IOException ex) {


System.out.println(ex);
}
} University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

PrintWriter
The JavaPrintWriterclass (java.io.PrintWriter) enables you to write formatted data
to an underlyingWriter.
ThePrintWriterclass has all the same methods as thePrintStream except for the
methods to write raw bytes. Being aWritersubclass thePrintWriteris intended to
write text.
void print(boolean b) import java.io.*;
void print(char c) public class PrintStreamExample {
void print(double d)
void print(float f) public static void main(String[] args) {
void print(int i) int x = 5;
void print(long l)
// create printstream object
void print(String s)
PrintStream ps = new
void println() PrintStream(System.out);
void println(boolean x)
void println(char x) // print integer
void println(double x) ps.println(x);
void println(float x) ps.println(100);
void println(int x) ps.print(12.56);
}
void println(long x)
}
void println(String x)
University
and many more.. Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

read() and readLine()


read() readLine()
the read() method reads a single readLine() method accepts a string
character from the keyboard. from the keyboard
char ch = br.read(); BufferedReader br=new
BufferedReader();
String str = br.readLine();

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Taking input from the keyboard:

1. Console
2. Scanner

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Console
In java, Console class is used to read the input provided
from console by the user. It can be used to data like text
and password. Typed password will not be visible on the
console.
Console class Methods:

Console format(String fmt, Object args):


Console printf(String fmt, Object args):
public String readLine():Reads a line from console.
public String readLine(String fmt,Object args):It provides a
formatted prompt then reads the single line of text from the console.
public char[] readPassword():Reads password from console.
Password is not visible at console.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Console(contd.)
Console class Methods:

Console format(String fmt, Object args):

import java.io.*;
class Console_program {
public static void main(String[]
args) {
Console console =
System.console();

console.format("%d\n",
12345678);
console.format("%04d%04d\n",
12, 34);
console.format("%4d%4d\n", 12,
34); University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Console(contd.)
Console printf(String fmt):

import java.io.*;
class Console_program {
public static void main(String[]
args) {
Console console =
System.console();
console.printf("Java
programming");

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Console(contd.)
public String readLine():Reads a line from console.

import java.io.*;
class Console_program {
public static void main(String[] args) {
Console console = System.console();
String line=console.readLine();
System.out.println("You have entered: ");
System.out.println(line);

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

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

import java.io.*;
class Console_program {
public static void main(String[] args) {
Console console = System.console();
String line = console.readLine("%d-%02d-%02d: ",
1, 2, 2015);
System.out.println(line);

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Console(contd.)
public char[] readPassword():Reads
password
from console with echoing disabled. Password
is not visible at console.
import java.io.*;
class Console_program {
public static void main(String[] args) {
Console console = System.console();
char[] password;
password =
console.readPassword("Password: ");
System.out.println(password);

}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Multithreading
Multi threading: Thread Life cycle,
Multi threading advantages and
issues, Simple thread program,
Thread synchronization.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Multithreading
Java is a multi threaded programming languagewhich means we can develop multi
threaded program using Java. A multi threaded program contains two or more parts
that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.
The main purpose of multithreading is to provide simultaneous execution of two or
more parts of a program to maximum utilize the CPU time. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called a thread. Each thread has a separate path of its execution. So this way a
single program can perform two or more tasks simultaneously.

Threads are lightweight processes; they share the same address space. In
Multithreaded environment, programs make maximum use of CPU so that the idle
time can be kept to minimum.

There are several thread states, A thread can be in any one of the state at a
particular point of time. It can be running state. It can be ready to run state as
soon as it gets CPU time. A running thread can be suspended. A suspended thread
can be resumed. A thread can be blocked when waiting for a resource. At any time
a thread can be terminated.
Thread is executed inside the process. There is context-switching between the
threads. There can be multiple processes inside the OS and one process can have
multiple threads.
Note: At a time one thread is executed only.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Life Cycle of a thread
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.
Running: 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.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Thread vs Process
Process Thread
A program in execution is often A thread is a subset(part) of the
referred as process process.
A process consists of multiple threads. A thread is a smallest part of the
process that can execute concurrently
with other parts(threads) of the
process.
A process is sometime referred as A thread is often referred as
task. lightweight process.
A process has its own address space. A thread uses the processs address
space and share it with the other
threads of that process.
A process can communicate with A thread can communicate with other
other process by usinginter-process thread (of the same process) directly
communication. by using methods like wait(), notify(),
notifyAll().

A process does not have control over Threads have control over the other
the sibling process, it has control over threads of the same process
its child processes only.
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Multiprogramming, Multiprocessing,
Multitasking
Multiprogramming - A computer running more
than one program at a time (like running Excel
and Firefox simultaneously)
Multiprocessing - A computer using more than
one CPU at a time.
Multitasking - Tasks sharing a common
resource (like 1 CPU)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Multitasking

Multitasking
Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each
process allocates separate memory area.
Process is heavyweight.
Cost of communication between the process is high.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Advantage of Java
Multithreading
Itdoesn't block the userbecause threads are independent
and you can perform multiple operations at same time.
Youcan perform many operations together so it saves
time.
Threads areindependentso it doesn't affect other threads if
exception occur in a single thread.
Context switching between threads is usually less expensive
than between processes.
Disadvantage of Java
Multithreading
More complex design and coding
Context Switching Overhead
Deadlocks (very hard to debug logical program
errors)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Running threads
Example
class mythread implements Runnable{
public void run(){
System.out.println(Thread Started);
}
}

class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
Calling t.run() does not start a thread, it is just a
simple method call.
Creating an object does not create a thread, calling
start() method creates the thread.
You can start() multiple thread but at one time only
one thread will run.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

The MAIN Thread


THE MAIN THREAD
As anyJava program comes under execution, first thread starts
immediately, called themain thread.There are two
importance's of main thread as follows:
It is the parent of all the threads of the program and all other
"child" threads will be spawned form it.
It must be the last thread to finish the execution of the program.
As your program start, the main thread is created automatically,
under the control of Thread object. But, if you want the
reference of the main thread then there is a static
methodcurrentThread()of Thread class, which returns the
reference of thread in which it is called.
Eg, Thread t = Thread.currentThread();
t.setName("My Thread");

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

2 ways to create threads

Creating and Starting Threads


Creating a thread in Java is done like this:
Thread t = new Thread();
To start the thread you will call its start() method, like this:
t.start();
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

2 ways to create threads


(contd.)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

1st Way : Extending Thread Class


Creating thread by extending Thread class
1. Let your class extend Thread class
2. Now override the public void run() method and write your logic there
(This is the method which will be executed when this thread is started)
Thats it, now you can start this thread as given below
1. Create an object of the above class
2. Call the method start on the object created. Now our thread will start
its execution in parallel.

//By extending Thread class


classMultiextendsThread
{
publicvoidrun()
{
System.out.println("threadisrunning.
..");
}
publicstaticvoidmain(Stringargs[]
){
Multi t1=new Multi();
t1.start();
}
University Institute of Engineering (UIE)
class Thread_class1 extends Thread
{ Department of Computer Science and Engineering (CSE)
public void run()
{
1st Way : Extending
for(int i=0;i<10;i++)
{
Thread Class:
System.out.println("Thread class1: "+i);
try{ Using single class file
Thread.sleep(1000);}
catch(InterruptedException e){}
}
}
}

class Thread_class2 extends Thread


{
public void run()
{
for(int i=10;i<20;i++)
{
System.out.println("Thread class2: "+i);
try{
Thread.sleep(1000);}
catch(InterruptedException e){}
}
}
}

class Thread_class
{
public static void main(String ar[])
{
Thread_class1 t1=new Thread_class1();
Thread_class2 t2=new Thread_class2();

t1.start();
t2.start();
}
} University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

1st Way : Extending Thread Class: Using


multiple class files
(contd.)
Demo Code - Creating Thread by extending
Thread class
In this example, we will create two threads
FirstThread and SecondThread.Both of
these threads will display numbers 1, 2, 310
with a one second delay in displaying the next
number. ThreadDemo class will be starting
these threads FirstThread and
SecondThread.

University Institute of Engineering (UIE)


//This class is made as a thread by extending "Thread"
//This class is made as a thread by extending "Thread"
class.
Department of Computer class. Science and Engineering (CSE)
public class FirstThread extends Thread
public class SecondThread extends Thread
{
//This method will be executed when this thread is {
executed
//This method will be executed when this thread is
public void run()
executed
{
public void run()
{
//Looping from 1 to 10 to display numbers from 1 to
//Looping from 1 to 10 to display numbers from 1 to
10
for (int i=1; i<=10; i++) 10
for (int i=1; i<=10; i++)
{
{
//Displaying the numbers from this thread
System.out.println( "Messag from Second Thread : "
System.out.println( "Messag from First Thread : "
+i); +i);
try
{
try
{ Thread.sleep (1000);
}
Thread.sleep(1000);
catch (InterruptedException interruptedException)
}
{
catch (InterruptedException interruptedException)
{ /*Interrupted exception will be thrown when a
sleeping or waiting thread is interrupted.
/*Interrupted exception will be thrown when a
*/
sleeping or waiting thread is interrupted.
*/ System.out.println( "Second Thread is interrupted
when it is sleeping" +interruptedException);
System.out.println( "First Thread is interrupted
}
when it is sleeping" +interruptedException);
}
}
} }
}
}
* "Thread.sleep(1000);" - when this statement is executed,
} * this thread will sleep for 1000 milliseconds (1 second)
before executing the next statement.
* Since we are making this thread to sleep for one second,
we need to handle "InterruptedException". Our thread may throw
this exception if it is interrupted while it is sleeping.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
1 Way : Extending Thread Class: Using
st

multiple class files


(contd.)
public class ThreadDemo
{
public static void main(String args[])
{

//Creating an object of the first thread


FirstThread firstThread = new FirstThread();

//Creating an object of the Second thread


SecondThread secondThread = new SecondThread();

//Starting the first thread


firstThread.start();

//Starting the second thread


secondThread.start();
}
}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

2nd Way : Implementing


Runnable Interface
Runnable Interface Implemention
The second way to specify what code a thread should run is
by creating a class that implements java.lang.Runnable.
The Runnable object can be executed by a Thread.
1.Declare the class as implementing the runnable interface.
2. Implement run() method.
Create thread by defining an object that is instantiated from
this runnable class the target of the thread.
Here is a JavaRunnableexample:
public class MyRunnable implements Runnable
{ public void run()
{ System.out.println("MyRunnable running");
}}

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
2nd Way : Implementing
Runnable Interface (contd.)
Implementing the Runnable interface
classMulti3implementsRunnable{
publicvoidrun(){
System.out.println("threadisrunning...");
}

publicstaticvoidmain(Stringargs[]){
Multi3m1=newMulti3();
Threadt1=newThread(m1);
t1.start();
}
}
Output:thread is running...
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
Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)
Difference between extends
Thread class and implements
interface
Inheritance Option: The limitation with extends Thread
approach is that if you extend Thread, you cannot extend
anything else. Java does not support multiple inheritance.
Implementing the Runnable interface gives you the choice to
extend any class you like.
Loosely-coupled: implements Runnable makes the code
loosely-coupled and easier to read.
Functions overhead: extends Thread means inheriting all the
functions of the Thread class which we may do not need.
In the Runnable interface approach, only one
instance of a class is being created and it has been
shared by different threads. So the value of counter is
incremented for each and every thread access.

Whereas, Thread class approach, you must have to


create separate instance for every thread access.
Hence different memory is allocated for every class
instances and each has separate counter, the value
remains same, which means no increment will happen
University
because none ofInstitute
the object of Engineering
reference is same. (UIE)
Department of Computer
//Implement Runnable Interface... Science and Engineering (CSE)
class ImplementsRunnable implements Runnable {

private int counter = 0; public class ThreadVsRunnable {

public void run() { public static void main(String args[]) throws Exception {
counter++; // Multiple threads share the same object.
System.out.println("ImplementsRunnable : Counter : " ImplementsRunnable rc = new ImplementsRunnable();
+ counter); Thread t1 = new Thread(rc);
} t1.start();
} Thread.sleep(1000); // Waiting for 1 second before
starting next thread
//Extend Thread class... Thread t2 = new Thread(rc);
class ExtendsThread extends Thread { t2.start();
Thread.sleep(1000); // Waiting for 1 second before
private int counter = 0; starting next thread
Thread t3 = new Thread(rc);
public void run() { t3.start();
counter++;
System.out.println("ExtendsThread : Counter : " + // Creating new instance for every thread access.
counter); ExtendsThread tc1 = new ExtendsThread();
} tc1.start();
} Thread.sleep(1000); // Waiting for 1 second before
starting next
thread
ExtendsThread tc2 = new ExtendsThread();
tc2.start();
Thread.sleep(1000); // Waiting for 1 second before
starting next
thread
ExtendsThread tc3 = new ExtendsThread();
When to use Runnable? tc3.start();
Use Runnable interface when you want to access the }
same resource from the group of threads. Avoid using }
Thread class here, because multiple objects creation
University Institute of Engineering (UIE)
consumes more memory and it becomes a big
Department of Computer Science and Engineering (CSE)

Synchronization

At times when more than one thread try to access a shared


resource, we need to ensure that resource will be used by only one
thread at a time. The process by which this is achieved is
calledsynchronization.
Consider an example, Suppose we have two different
threadsT1andT2, T1 starts execution and save certain values in a
filetemporary.txtwhich will be used to calculate some result when
T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change
the values saved by T1 in the file temporary.txt (temporary.txt is the
shared resource). Now obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With
synchronization in above case, once T1 starts
usingtemporary.txtfile, this file will belocked(LOCK mode), and no
other thread will be able to access or modify it until T1 returns.
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. This is implemented using a concept calledmonitors.
Each object in Java is associated with a monitor, which a thread can
lock or unlock. Only one thread at a time may hold a lock on a
monitor.

University Institute of Engineering (UIE)


class First
{ Department of Computer Science and Engineering (CSE)
public void display(String msg)
{
System.out.print ("["+msg);
try
{

}
Thread.sleep(1000);
Example without
catch(InterruptedException e)
{ synchronization
e.printStackTrace();
}
System.out.println ("]");
} In the above program, objectfnewof
}
class First is shared by all the three
class Second extends Thread
{ running threads(ss, ss1 and ss2) to
Thread t;
String msg; call the shared method(voiddisplay).
First fobj;
Second (First fp,String str)
Hence the result is unsynchronized
{ and such situation is calledRace
fobj = fp;
msg = str; condition.
t=new Thread(this);
t.start();
}
public void run()
{
fobj.display(msg);
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
} University Institute of Engineering (UIE)
class First
{ Department of Computer Science and Engineering (CSE)
public void display(String msg)
{
System.out.print ("["+msg);
try Example with
{

}
Thread.sleep(1000); synchronization
catch(InterruptedException e)
{
e.printStackTrace();
} Synchronized Keyword : To synchronize above
System.out.println ("]");
} we mustserializeaccess to the shareddisplay()
}
method, making it available to only one thread at
class Second extends Thread
{
time. This is done by using keywordsynchronize
String msg;
First fobj;
with display() method.
Second (First fp,String str) synchronized void display (String msg)
{
fobj = fp; Using Synchronised block : If you have to sync
msg = str;
start(); access to object of a class that has no synchroniz
}
public void run() methods, you can use
{
synchronized(fobj) //Synchronized block
synchronized block .
{
fobj.display(msg);
}
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
University Institute of Engineering (UIE)
Second ss2 = new Second(fnew, "programmer");
Department of Computer Science and Engineering (CSE)

When we declare a method synchronized, java creates a


monitor and hands it over to thread that calls the method first
time.
As long as thread holds the monitor, no other thread can enter
the synchronized section of code.
A monitor is like a key and the thread that holds the key can
open the lock.
Whenever a thread has completed its work of using
synchronized method,
it will hand over the monitor to the next thread that is ready
to use the same resource.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Methods
join():It makes to wait for this thread to die. You can
wait for a thread to finish by calling its join() method.
sleep():It makes current executing thread to sleep for
a specified interval of time. Time is in milli seconds.
yield():It makes current executing thread object to
pause temporarily and gives control to other thread to
execute.
wait():This method makes current thread to wait until
another thread invokes the notify() or the notifyAll() for
this object.
notify():This method wakes up a single thread that is
waiting on this object's monitor to acquire lock.
notifyAll(): This method wakes up all threads that are
waiting on this object's monitor to acquire lock.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

THREAD PRIORITIES
Thread priorities are the integers which decide how one
thread should be treated with respect to the others.
Thread priority decides when to switch from one running
thread to another, process is called context switching
A thread can voluntarily release control and the highest
priority thread that is ready to run is given the CPU.
A thread can be preempted by a higher priority thread no
matter what the lower priority thread is doing. Whenever a
higher priority thread wants to run it does.
To set the priority of the threadsetPriority()method is used
which is a method of the classThreadClass. In place of
defining the priority in integers,
useMIN_PRIORITY,NORM_PRIORITYor MAX_PRIORITY.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

THREAD PRIORITIES
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
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.

University Institute of Engineering (UIE)

Vous aimerez peut-être aussi