0% found this document useful (0 votes)
2 views62 pages

Unit - 3

The document provides an overview of Input/Output (I/O) operations in Java, focusing on the java.io package and the concept of streams. It explains standard input, output, and error streams, as well as the differences between byte and character streams, including their respective classes like FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it covers methods for reading and writing data, handling exceptions, and introduces the concept of multitasking in Java.

Uploaded by

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

Unit - 3

The document provides an overview of Input/Output (I/O) operations in Java, focusing on the java.io package and the concept of streams. It explains standard input, output, and error streams, as well as the differences between byte and character streams, including their respective classes like FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it covers methods for reading and writing data, handling exceptions, and introduces the concept of multitasking in Java.

Uploaded by

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

JAVA PROGRAMMING

UNIT 3
I/O in Java
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast.
The process of reading & writing objects is called “object serialization”.
The java.io package contains all the classes required for input and output operations. We can
perform file handling in Java by Java I/O API.
The Java IO API is placed in the java.io package. This package comprises almost all classes that a
user requires to perform input and output (I/O) in Java. The Java IO package focuses on input and
output to files, network streams, etc.
The java.io package generally involves reading basic information from a source and writing it to a
destination.
Java uses the concept of a stream to make I/O operation fast.

SWATI JAIN, VIPS TC 2


Streams in Java
A stream is a sequence of data. In Java, a stream is
composed of bytes. It's called a stream because it is like
a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All
these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Like an array, a stream has no concept of indexing the
read or written data.
A stream is attached to a data origin or a data target.

SWATI JAIN, VIPS TC 3


Standard Streams
• All the programming languages assist standard I/O, where the user’s program can take input from a keyboard and then produce
an output on the computer screen. Just like C and C++ have three standard streams, STDIN, STDOUT, and STDERR, Java also
provides the following three standard streams:
• Standard Input – The Standard Input class is used to accept input data to the user’s program. Usually, a keyboard is utilized as a
standard input stream and described as System.in.

• Standard Output – This class is used to output the data generated by the user’s program, and usually, a computer screen is used
for standard output stream and described as System.out.

• Standard Error – The Standard error class is used to output the data having an error that is generated by the user’s program.
Normally, a computer screen is utilized for standard error stream and described as System.err.

SWATI JAIN, VIPS TC 4


Standard Streams
// Java program to illustrate the Standard Java IO Streams
catch (Exception ex) {
import java.io.*;
// using System.err class to print the error message
import java.util.*; System.err.print("Exception message : "+
public class StandardStreamsExample { ex.getMessage());
public static void main(String[] args) }
}
{
}
try {

Scanner s = new Scanner(System.in);

// using System.out class to print the output on the screen using .print() and .println()

System.out.print("Enter the value of A : ");

int a = s.nextInt();

System.out.println("Value of A is : " + a);

System.out.print("Enter the value of B : ");

int b = s.nextInt();

System.out.println("Value of B is : " + b);

System.out.println( "Result of division A/B is : " + (a / b));

SWATI JAIN, VIPS TC 5


Streams in Java

SWATI JAIN, VIPS TC 6


OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

SWATI JAIN, VIPS TC 7


InputStream
An input stream is used to read the data from a source in a Java application. Data can be anything, a
file, an array, a peripheral device, or a socket.
In Java, the class java.io.InputStream is the base class for all Java IO input streams.

SWATI JAIN, VIPS TC 8


Methods of Java IO InputStreams
1. read() – method is used to read the next byte of data from the Input Stream. The value byte is passed on a scale of 0 to 255. If no byte
is free because the end of the stream has arrived, the value -1 is passed.

2. mark(int arg) – method is used to mark the current position of the input stream. It sets read to limit, i.e., the maximum number of bytes
that can be read before the mark position becomes invalid.

3. reset() – method is invoked by mark() method. It changes the position of the input stream back to the marked position.

4. close() – method is used to close the input stream and releases system resources associated with this stream to Garbage Collector.

5. read(byte [] arg) – method is used to read the number of bytes of arg.length from the input stream to the buffer array arg. The bytes
read by read() method are returned as an int. If the length is zero, then no bytes are read, and 0 is returned unless there is an effort to
read at least one byte.

6. skip(long arg) – method is used to skip and discard arg bytes in the input stream.

7. markSupported() – The method tests if the inputStream supports the mark and reset methods. The markSupported method of Java IO
InputStream yields false by default.

SWATI JAIN, VIPS TC 9


// Java program illustrates the use of
// the Java IO InputStream methods }
catch(Exception e)
import java.io.*; {
// in case of I/O error
public class InputStreamExample e.printStackTrace();
{ }
public static void main(String[] args) throws Exception finally
{ {
InputStream input = null; if (input!=null)
try { {
// Use of close() - closing the file
input = new FileInputStream("Text.txt"); // and releasing resources
// read() method - reading and printing Characters input.close();
// one by one }
System.out.println("Char - "+(char)input.read()); }
System.out.println("Char - "+(char)input.read()); }
// skip() - it results in skipping of 'e' in Ge'e'ksforGeeks }
input.skip(1);
System.out.println("skip() method comes to play");
System.out.println("mark() method comes to play");
System.out.println("Char - "+(char)input.read());
System.out.println("Char - "+(char)input.read());
boolean check = input.markSupported();

SWATI JAIN, VIPS TC 10


OutputStream
An output stream is used to write data (a file, an array, a peripheral device, or a socket) to a
destination. In Java, the class java.io.OutputStream is the base class for all Java IO output streams.

SWATI JAIN, VIPS TC 11


Methods of Java IO OutputStreams
Methods of Java IO OutputStreams
1.flush() – The flush() method is used for flushing the outputStream This method forces the buffered
output bytes to be written out.

2.close() – The close() method is used to close the outputStream and to release the system resources
affiliated with the stream.

3.write(int b) – The write(int b) method is used to write the specified byte to the outputStream.

4.write(byte [] b) – The write(byte [] b) method is used to write bytes of length b.length from the
specified byte array to the outputStream.

SWATI JAIN, VIPS TC 12


// Java program to demonstrate OutputStream
import java.io.*;
public class OutputStreamExample {
public static void main(String args[]) throws Exception
{
OutputStream output = new FileOutputStream("file.txt");
byte b[] = { 65, 66, 67, 68, 69, 70 };
// illustrating write(byte[] b) method
output.write(b);

// illustrating flush() method


output.flush();

// illustrating write(int b) method


for (int i = 71; i < 75; i++) {
output.write(i);
}
output.flush();
// close the stream
output.close();
}
}

SWATI JAIN, VIPS TC 13


Types of Streams in Java IO

SWATI JAIN, VIPS TC 14


Byte Streams
•Java byte streams are the ones
that are used to implement the
input and output of 8-bit bytes.
•All byte stream classes are derived
from base abstract classes called
InputStream and OutputStream.
•Several classes are affiliated with
byte streams in Java. However, the
most generally practiced classes
are
•FileInputStream and
• FileOutputStream.

SWATI JAIN, VIPS TC 15


Character Streams
• Java Character streams are the ones that
are used to implement the input and output
for 16-bit Unicode.
• All the character stream classes are derived
from base abstract classes Reader and
Writer.
•Several classes are associated with
character streams in Java, but the most
c o m m o n l y u s e d c l a s s e s
are FileReader and FileWriter.
• I n t e r n a l l y, t h e F i l e R e a d e r c l a s s u s e s
FileInputStream and the FileWriter class
uses FileOutputStream.
• Nevertheless, the significant contrast is that
FileReader and FileWriter read and write
two bytes, respectively.

SWATI JAIN, VIPS TC 16


File I/O using Byte Stream - FileInputStream Class
Java FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc.
You can also read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.
Declaration: public class FileInputStream extends InputStream

SWATI JAIN, VIPS TC 17


SWATI JAIN, VIPS TC 18
SWATI JAIN, VIPS TC 19
File I/O using Byte Stream - FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-
oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
declaration : public class FileOutputStream extends OutputStream

SWATI JAIN, VIPS TC 20


SWATI JAIN, VIPS TC 21
SWATI JAIN, VIPS TC 22
File I/O using Character Stream – FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Declaration: public class FileReader extends InputStreamReader

SWATI JAIN, VIPS TC 23


File I/O using Character Stream – FileReader Class

SWATI JAIN, VIPS TC 24


File I/O using Character Stream – FileWriter Class
Java FileWriter class is a character-oriented class which is used to write character-oriented data to a file.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to
write string directly.
Declaration: public class FileWriter extends OutputStreamWriter

SWATI JAIN, VIPS TC 25


File I/O using Character Stream – FileWriter Class

SWATI JAIN, VIPS TC 26


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

// attach a file to FileWriter


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

// read character wise from string and write


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

System.out.println("Writing successful");
//close the file
fw.close();
}
}
SWATI JAIN, VIPS TC 27
// Reading data from a file using FileReader
// read from FileReader till the end of file
import java.io.FileNotFoundException;
while ((ch=fr.read())!=-1)
import java.io.FileReader;
System.out.print((char)ch);
import java.io.IOException;
class ReadFile
// close the file
{
fr.close();
public static void main(String[] args) throws IOException
}
{
}
// variable declaration
int ch;

// check if File exists or not


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

SWATI JAIN, VIPS TC 28


TASK CHARACTER STREAM CLASS BYTE STREAM CLASS

INPUT OPERATIONS Reader InputStream

WRITING TO A FILE FileWriter FileOutputStream

BUFFERING INPUT Buffered Reader BufferedInputStream

READING FROM FILES FileReader FileInputStream

SWATI JAIN, VIPS TC 29


Reading/Writing Characters - Copy Characters from one file to another
import java.io.* while(( ch=ins.read()) ! = -1)
Class copy {
{ outs.write(ch);
public static void main(String args[]) }}
{
catch(IOException e)
File in = new File(“Input.dat”);
File out = new File(“Output.dat”); {
FileReader ins = null; System.out.println(e);
FileWriter outs = null; System.exit(-1);

try }
{ finally {
ins = new FileReader(in); try{
outs = new FileWriter(out);
ins.close();
outs.close();
// Read and Write till EOF }
int ch; catch(IOException e) { }
}}}

SWATI JAIN, VIPS TC 30


Reading/Writing Bytes - Writing Bytes to a file
import java.io.*
Class WriteBytes catch(IOException e)
{ {
public static void main(String args[]) System.out.println(e);
{
System.exit(-1);
byte city[] = {‘D’,’E’,’L’,’H’,’I’};
FileOutputStream outfile = null; }

try }
{
outfile = new FileOutputStream(“city.txt); }
outfile.write(city); }
outfile.close();
}

SWATI JAIN, VIPS TC 31


Reading/Writing Bytes - Reading Bytes from a file
import java.io.*
Class ReadBytes catch(IOException e)
{ {
public static void main(String args[]) System.out.println(e);
{
FileInputStream outfile = null; System.exit(-1);
char b; }
try
{
infile = new FileInputStream(“city.txt); }

while((b=infile.read())!=-1) }
{ }
System.out.println((char) b );
}

infile.close();
}

SWATI JAIN, VIPS TC 32


Input/Output Exceptions
When Creating files & performing I/O operations on them, the system may generate I/O related
exceptions.
The basic I/O related exception classes and their functions:
1. EOFException - Signals the end of file is reached
2. FileNotFoundException - Informs that a file was not found.
3. InterruptedException - warns that the I/O operation has been interrupted.
4. IOException - Signals that the IO Exception of some kind has occured.

SWATI JAIN, VIPS TC 33


Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can
be achieved in two ways:
•Process-based Multitasking (Multiprocessing)
•Each process has an address in memory. In other words, each process allocates a separate memory area.
•A process is heavyweight.
•Cost of communication between the process is high.
•Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists,
etc.

•Thread-based Multitasking (Multithreading)


Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.

SWATI JAIN, VIPS TC 34


Multithreading in Java
•Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.
•A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both
are used to achieve multitasking.
•However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process.

SWATI JAIN, VIPS TC 35


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

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

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

SWATI JAIN, VIPS TC 36


What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

As shown in the figure, there are multiple processes and each


process has multiple threads. A 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.

SWATI JAIN, VIPS TC 37


Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one
of the shown states at any instant:

New State
Runnable State
Blocked State
Waiting State
Timed Waiting State
Terminated State

SWATI JAIN, VIPS TC 38


Life Cycle of a Thread
New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the thread is in
this state. When a thread lies in the new state, its code is yet to be run and hasn’t started to execute.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two
states within it: one is runnable, and the other is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be
running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time
to run, i.e., moving the thread the running state.A program implementing multithreading acquires a fixed slice of time to
each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the
thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable
state. In the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most
common change in the state of a thread is from runnable to running and again back to runnable.Blocked: The thread will
be in blocked state when it is trying to acquire a lock but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the lock.

SWATI JAIN, VIPS TC 39


Life Cycle of a Thread
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked
state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the
other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use
the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus
never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread then
waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the main
thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which thread
to choose and which one to reject, and the chosen thread is then given the opportunity to run.

SWATI JAIN, VIPS TC 40


Life Cycle of a Thread
Timed Waiting: Sometimes, waiting leads to starvation. For example, a thread (its name is A) has entered the critical section of
a code and is not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting
state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start
its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can
respawn (active after kill) the dead thread.

SWATI JAIN, VIPS TC 41


Creation of Threads
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the
Thread class. A thread begins its life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we
instantiate a Thread object and call start() method on this object.

SWATI JAIN, VIPS TC 42


Thread Class
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


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

SWATI JAIN, VIPS TC 43


Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.

SWATI JAIN, VIPS TC 44


Commonly used methods of Thread class:
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.

SWATI JAIN, VIPS TC 45


The Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

SWATI JAIN, VIPS TC 46


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

SWATI JAIN, VIPS TC 48


Threads using Thread class
// Java code for thread creation by extending the Thread class
// Main Class
class MultithreadingDemo extends Thread { public class Multithread {
public void run()
public static void main(String[] args)
{
{ int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
try {
MultithreadingDemo object
// Displaying the thread that is running = new MultithreadingDemo();
object.start();
System.out.println("Thread " + Thread.currentThread().getId() }
+ " is running"); }
}
}

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

} }}
SWATI JAIN, VIPS TC 49
Threads using Runnable Interface
// Java code for thread creation by implementing catch (Exception e) {
// the Runnable Interface // Throwing an exception
System.out.println("Exception is caught");
class MultithreadingDemo implements Runnable { }
}
public void run()
}
{ // Main Class
class Multithread {
try {
public static void main(String[] args)
// Displaying the thread that is running {
int n = 8; // Number of threads
System.out.println( for (int i = 0; i < n; i++) {
"Thread " + Thread.currentThread().getId() Thread object
= new Thread(new MultithreadingDemo());
+ " is running"); object.start();
}
}
}
}

SWATI JAIN, VIPS TC 50


Thread Class vs Runnable Interface

If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple
inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in Runnable interface.
Using runnable will give you an object that can be shared amongst multiple threads.

SWATI JAIN, VIPS TC 51


Wait and Sleep Methods in Java
In Java, wait and sleep are the concept of multithreading. Wait and Sleep are the methods used to
pause a process for few seconds and go a thread in the waiting state, respectively.
Sleep()
The Sleep () method is related to the Thread class that is used to stop the execution of the current
Thread for few seconds. The Sleep () method takes the sleeping time in milliseconds. The monitor's
ownership is not lost when we use the Sleep () method and start the execution again from where it
stops. In simple words, the Sleep() method is responsible for sending the current Thread into the
"Non Runnable" state.

Wait()
The Wait() method is related to the Object class. The Wait() method is responsible for sending the
calling thread into the waiting state. The Thread remains in the waiting state until another thread
doesn't invoke the notify() or notifyAll() method for that object. The Thread resumes the execution
after obtaining the ownership of the monitor.

SWATI JAIN, VIPS TC 52


Similarities between wait and sleep methods
class WaitSleepSimilaritiesExample
{

//create an instance of the Object


private static Object obj = new Object();

//main() method starts with handling InterruptedException


public static void main(String[] args)throws InterruptedException
{
//pause process for two second
Thread.sleep(2000);
//print custom statement
System.out.println( Thread.currentThread().getName() + " Thread is woken after two second");
//create synchronizec context from which we call Wait() method
synchronized (obj)
{
//use wailt() method to set obj in waiting state for two seconds
obj.wait(2000);
System.out.println(obj + " Object is in waiting state and woken after 2 seconds");
} } }

SWATI JAIN, VIPS TC 53


Difference b/w Wait() and Sleep()

SWATI JAIN, VIPS TC 54


Killing threads in Java
ØA thread is automatically destroyed when the run() method has completed. But it might be required
to kill/stop a thread before it has completed its life cycle.
ØPreviously, methods suspend(), resume() and stop() were used to manage the execution of threads.
ØBut these methods were deprecated by Java 2 because they could result in system failures.
ØModern ways to suspend/stop a thread are by using a boolean flag and Thread.interrupt() method.

SWATI JAIN, VIPS TC 55


Java Thread suspend() public class JavaSuspendExp extends Thread
{ public void run()

method { for(int i=1; i<5; i++)


{
try
The suspend() method of thread class {
puts the thread from running to waiting // thread to sleep for 500 milliseconds
state. sleep(500);
This method is used if you want to stop System.out.println(Thread.currentThread().getName());
the thread execution and start it again }catch(InterruptedException e){System.out.println(e);}
when a certain event occurs. System.out.println(i);
} }
This method allows a thread to public static void main(String args[])
temporarily cease execution. The
{
suspended thread can be resumed
using the resume() method. // creating three threads
JavaSuspendExp t1=new JavaSuspendExp ();
JavaSuspendExp t2=new JavaSuspendExp ();
JavaSuspendExp t3=new JavaSuspendExp ();
// call run() method
t1.start();
t2.start();
// suspend t2 thread
t2.suspend();
// call run() method
t3.start();
} }
SWATI JAIN, VIPS TC 56
Java Thread resume() public class JavaResumeExp extends Thread
{ public void run()

method { for(int i=1; i<5; i++)


{ try
{
The resume() method of thread class is // thread to sleep for 500 milliseconds
only used with suspend() method. sleep(500);
This method is used to resume a thread System.out.println(Thread.currentThread().getName());
which was suspended using suspend() }catch(InterruptedException e){System.out.println(e);}
method. System.out.println(i);
} }
This method allows the suspended public static void main(String args[])
thread to start again. { // creating three threads
JavaResumeExp t1=new JavaResumeExp ();
JavaResumeExp t2=new JavaResumeExp ();
JavaResumeExp t3=new JavaResumeExp ();
// call run() method
t1.start();
t2.start();
t2.suspend(); // suspend t2 thread
// call run() method
t3.start();
t2.resume(); // resume t2 thread
}
}

SWATI JAIN, VIPS TC 57


Java Thread stop() method public class JavaStopExp extends Thread
{
public void run()
{
The stop() method of thread class for(int i=1; i<5; i++)
terminates the thread execution. {
Once a thread is stopped, it cannot try
be restarted by start() method. {
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
Syntax System.out.println(i);
}
public final void stop() }
public static void main(String args[])
public final void stop(Throwable obj) {
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
t1.start();
t2.start();
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}

SWATI JAIN, VIPS TC 58


Multithreading Synchronization
Synchronization — is the capability to control the access of multiple threads to any shared resource.
Multithreaded programs may often come to a situation where multiple threads try to access the same shared resources.
Synchronization helps prevent non-deterministic state of an object.
Need of Thread Synchronization?
When we start two or more threads within a program, there may be a situation when multiple threads try to access the
same resource and finally they can produce unforeseen result due to concurrency issues.
For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads
can override data or while one thread is opening the same file at the same time another thread might be closing the same
file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource
at a given point in time. This is implemented using a concept called monitors.
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.

SWATI JAIN, VIPS TC 59


Thread Synchronization in Java
Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of the
synchronized statement −

Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents. Now we are going to see two examples, where we will print a counter using
two different threads. When threads are not synchronized, they print counter value which is not in sequence, but
when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for
both the threads.

SWATI JAIN, VIPS TC 60


Multithreading Example without Thread Synchronization
Here is a simple example which may or may not print counter value in sequence and every time we run it, it
produces a different result based on CPU availability to a thread.
class PrintDemo { if (t == null) {
public void printCount() { t = new Thread (this, threadName);
try { t.start ();
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i ); }
} }}
} catch (Exception e) { public class TestThread {
System.out.println("Thread interrupted."); public static void main(String args[]) {
}} } PrintDemo PD = new PrintDemo();
class ThreadDemo extends Thread { ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
private Thread t; ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
private String threadName; T1.start();
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
T2.start();
threadName = name; // wait for threads to end
PD = pd; } try {
public void run() { T1.join();
PD.printCount(); T2.join();
System.out.println("Thread " + threadName + " exiting."); } } catch ( Exception e) {
public void start () { System.out.println("Interrupted");
System.out.println("Starting " + threadName );
} }}
This produces a different result every time you run this
program

SWATI JAIN, VIPS TC 61


Multithreading Example with Thread Synchronization
Here is the same example which prints counter value in sequence and every time we run it, it produces the
same result.
public void start () {
class PrintDemo { System.out.println("Starting " + threadName );
public void printCount() {
if (t == null) {
try {
for(int i = 5; i > 0; i--) {
t = new Thread (this, threadName);
System.out.println("Counter --- " + i ); t.start ();
} }}}
} catch (Exception e) { public class TestThread {
System.out.println("Thread interrupted."); public static void main(String args[]) {
} }} PrintDemo PD = new PrintDemo();
class ThreadDemo extends Thread {
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
private Thread t;
private String threadName;
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
PrintDemo PD; T1.start();
ThreadDemo( String name, PrintDemo pd) { T2.start();
threadName = name; // wait for threads to end
PD = pd; try {
} T1.join();
public void run() {
T2.join();
synchronized(PD) {
PD.printCount();
} catch ( Exception e) {
} System.out.println("Interrupted");
System.out.println("Thread " + threadName + " exiting."); } }}
} This produces same result every time you run this program

SWATI JAIN, VIPS TC 62

You might also like