Académique Documents
Professionnel Documents
Culture Documents
JAVA IO
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);
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());
}
}
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());
}
}
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.
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.
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
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.)
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)
Stream Classes(contd.)
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.
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
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.
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.
FileInputStream(contd.)
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);}
}
}
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.
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.)
i=fin.read();
System.out.print((char)i);
}
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.
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);}
}
}
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.
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
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());
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
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().
}
}
try
{
String s="Java Programming";
bout.write(s.getBytes());
}
finally
{
bout.close();
}
}
}
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.
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)
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.
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);}
}
}
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");
System.out.println(cbuf);
reader.close();
FileReader Methods(contd.)
System.out.println(cbuf);
reader.close();
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.
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);}
}
}
FileWriter Methods
Writing into a file using void write(char[] buf):
Writes an array of characters.
import java.io.*;
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.*;
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");
}
}
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");
}
}
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();
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();
}
}
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)
1. Console
2. Scanner
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(contd.)
Console class Methods:
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");
}
}
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);
}
}
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);
}
}
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);
}
}
Multithreading
Multi threading: Thread Life cycle,
Multi threading advantages and
issues, Simple thread program,
Thread synchronization.
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.
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)
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.
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)
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.
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)
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.
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
}
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);
}
}
}
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);
}
}
}
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.
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.
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.