Java Unit - 5 Notes
Java Unit - 5 Notes
MultiThreading
“Multithreading in java is a process of executing multiple threads simultaneously.”
Multiprocessing and multithreading, both are used to achieve multitasking.
What is Thread?
Multithreading enables to write very efficient programs that make maximum use of the
CPU.
It can perform many operations together so it saves time.
Threads are independent so it doesn't affect other threads if exception occurs in a single
thread.
It keeps CPU idle time to minimum.
It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
The Java language and its run-time system was designed keeping in mind about multithreading.
The run-time system depend upon multithreading. Java provides asynchronous thread
environment, this helps to increase the utilization of CPU.
1. Single Threaded program:
Single-thread system uses an approach of event loop with polling. In this model a single thread in
the system runs in an infinite loop. Polling mechanism which selects a single event from the
event queue to choose what to do next. As the event is selected, then event loop forwards the
NEC Page 1
control to the corresponding required event handler. Nothing else can be happened, until the
event handler returns. This wastes CPU time because only one part of a program dominating the
system and preventing any other events(threads) from being processed. That is, in a singled-
threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for
some resource, the entire program stops running.
2. Multi-Threaded program:
Java’s multithreading provides benefit in this area by eliminating the loop and polling mechanism,
one thread can be paused without stopping the other parts of the program. If any thread is paused
or blocked, still other threads continue to run.
Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets
CPU time. A running thread can be suspended, which temporarily suspends its activity. A
suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be
blocked when waiting for a resource. At any time, a thread can be terminated, which halts its
execution immediately. Once terminated, a thread cannot be resumed.
4. Thread Priorities
Thread priority in Java is a number assigned to a thread that is used by Thread
scheduler to decide which thread should be allowed to execute.Each thread has priority.
Higher-priority threads get more CPU time than lower-priority threads. Priorities are represented
by a number between 1 and 10.
A thread’s priority is used to decide when to switch from one running thread to the next. This is
called a context switch. The rules that determine when a context switch takes place is as follows:
A thread can voluntarily relinquish control: This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority
thread that is ready to run is given the CPU. •
In cases where two threads with the same priority are competing for CPU cycles, For operating
systems such as Windows, threads of equal priority are time-sliced automatically in round-robin
fashion.
5. Synchronization:
Synchronization in java is used to control the access of multiple threads to any shared
resource. Java Synchronization is used to allow only one thread to access the shared resource.
Synchronization is based on the entity known as the lock or monitor. Every object has a lock
associated with it. A thread that needs to access an object (resource) has to acquire the object's
NEC Page 2
lock before accessing them. It releases the lock when complete it's work with the acquired
resource.
a) synchronized block
b) synchronized method
Note: Once a thread is inside a synchronized method, no other thread can call any other
synchronized method on the same object. This enables you to write very clear and concise
multithreaded code.
6. Messaging
A program is a collection of more than one thread. Threads can communicate with each other.
Java supports messaging between the threads with lost-cost. It provides methods to all objects
for inter-thread communication. As a thread exits from synchronization state, it notifies all the
waiting threads.
Java’s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. Thread encapsulates a thread of execution. To create a new thread, your
program will either extend Thread or implement the Runnable interface.
Thread class provide constructors and methods to create and perform operations on a thread.
NEC Page 3
Waiting(blocked)
Dead (Terminated)
1. New state:
A new thread begins its life cycle in the new state.
It remains in this state until the program starts the thread (before calling the start()
method).
It is also referred to as a born thread.
2. Runnable state:
Runnable state is also called ready to run stage also called queue.
A thread start its life from Runnable state.
A thread first enters runnable state after the invoking of start() method.
3. Running state:
A thread is in running state that means the thread is currently executing.
A thread enters into a running state by calling run() method.
4. Waiting (Blocked):
NEC Page 4
A thread can enter in to a waiting state when a thread is waiting for the resources that
are hold by another thread.
A thread enters into a waiting state by calling either sleep() or wait() method.
5. Dead (Terminate) –
A thread can be considered dead when its run() method completes.
Once a Thread reached dead state it cannot run again.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.
Syntax: static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference to
the main thread, you can control it just like any other thread.
Example:
NEC Page 5
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
12345
Explanation:
In this program, a reference to the current thread (the main thread, in this case) is obtained
by calling currentThread( ), and this reference is stored in the local variable t. Next, the program
displays information about the thread. The program then calls setName( ) to change the internal
name of the thread. Information about the thread is then redisplayed. Next, a loop iterates 5 times,
pausing one second between each iteration. The pause is accomplished by the sleep( ) method. The
argument to sleep( ) specifies the delay period in milliseconds. Notice the try/catch block around
this loop. The sleep( ) method in Thread might throw an InterruptedException. This would happen
if some other thread wanted to interrupt this sleeping one. This example just prints a message if it
gets interrupted.
A thread group is a data structure that controls the state of a collection of threads as a whole.
sleep( ): The sleep() method is used to stop the execution of the current thread for a specified
time.
static void sleep(long milliseconds) throws InterruptedException
setName( ): The setName() method of thread class is used to change the name of the thread.
final String getName( )
Thread Class:
NEC Page 6
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): The sleep() method is used to sleep(suspend) a
thread for the specified amount of time. It throws an InterruptedException
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public boolean isDaemon(): tests if the thread is a daemon thread.
16. public void setDaemon(boolean b): marks the thread as daemon or user thread.
Thread Creation:
A thread is a single sequential flow of control within a program.
A thread is a lightweight sub-process, the smallest unit of processing.
NEC Page 7
1. By extending Thread class
One way to create a thread is to create a new class that extends Thread, and then to create
an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new
thread.
public void run( )
The second way to create a thread is to create a class that implements the Runnable
interface. Following are the steps to create a thread by implementing Runnable interface.
Define a class that implements Runnable interface
Implement the method run()
public void run( )
Create a thread by passing an object of this runnable class to the Thread class constructor
Call the thread’s start() method to run the thread.
Example:
Class A implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
NEC Page 8
public static void main(String args[])
{
A a=new A();
Thread t =new Thread(a);
t.start();
}
}
Output:thread is running...
Output:
B-1
A-1
A-2
A-3
B-2
B-3
isAlive( ) method:
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when
the start() method of thread class has been called and the thread is not yet dead. This method
returns true if the thread is still running and not finished.
isAlive( ) is used to determine whether a thread has finished or not.
Syntax:
public final boolean isAlive( )
This method will return true if the thread is alive otherwise returns false.
public class JavaIsAlive extends Thread
{
public void run()
{
try
{
Thread.sleep(3000);
System.out.println("Thread Running");
}
catch (InterruptedException ie) {
}
}
NEC Page 10
public static void main(String[] args)
{
JavaIsAlive t1 = new JavaIsAlive();
System.out.println("before starting thread isAlive: "+t1.isAlive());
t1.start();
System.out.println("after starting thread isAlive: "+t1.isAlive());
}
}
Output:
before starting thread isAlive: false
Thread Running
after starting thread isAlive: true
join() method:
The join() method which allows one thread to wait until another thread completes its execution.
The join() method waits for a thread to die. In other words, it causes the currently running threads
to stop executing until the thread it joins with completes its task.
Syntax:
Example-1
Output:
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by
using setName() method. The syntax of setName() and getName() methods are given below:
Example:
class ThreadName extends Thread
{
public void run()
{
System.out.println("running...");
}
public static void main(String args[])
{
ThreadName t1=new ThreadName();
ThreadName t2=new ThreadName();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
NEC Page 12
t2.start();
t1.setName("NECN");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
running...
running...
After changing name of t1:NECN
Thread Priorities
Thread priority in Java is a number assigned to a thread that is used by Thread
scheduler to decide which thread should be allowed to execute.
Each thread has priority. In theory, higher-priority threads get more CPU time than lower-
priority threads.
Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
The method throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum).
NEC Page 13
getPriority( ):
java.lang.Thread.getPriority() method returns priority of given thread.
Syntax: public final int getPriority( )
Example:
class MyThread extends Thread
{
public void run()
{
for (int j = 0; j < 5; j++)
{
System.out.println("child thread");
}
}
}
Example
class A extends Thread
{
public void run()
NEC Page 14
{
System.out.println(" thread name :"+Thread.currentThread().getName());
System.out.println(" thread priority :"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
A a1=new A();
A a2=new A();
a1.setPriority(Thread.MIN_PRIORITY);
a2.setPriority(Thread.MAX_PRIORITY);
//a2.setPriority(15); //IllegalArgumentException
a1.start();
a2.start();
}
}
Output:
thread name:Thread-0
thread priority:10
thread name:Thread-1
thread priority:1
Synchronization in Java
Synchronization in java is used to control the access of multiple threads to any shared
resource.
Java Synchronization is used to allow only one thread to access the shared resource.
Synchronization is based on the entity known as the lock or monitor. Every object has a
lock associated with it.
A thread that needs to access an object (resource) has to acquire the object's lock before
accessing them. It releases the lock when complete it's work with the acquired resource.
1. synchronized block
2. synchronized method
NEC Page 15
synchronized method
Syntax:
Syntax:
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<5;i++)
{
System.out.println(“Good Morning : ”);
try { Thread.sleep(1000); }
catch(InterruptedException e) { }
System.out.println(name);
}
}
}
synchronized block
synchronized (object )
{
//code block
}
Example:
class Display
{
public void wish(String name)
{
NEC Page 17
Synchronized(this) // synchronized block
{
for(int i=0;i<5;i++)
{
System.out.println(“Good Morning : ”);
try { Thread.sleep(1000); }
catch(InterruptedException e) { }
System.out.println(name);
}
}
}
}
Java-Stream Classes
Stream in Java represents sequential flow of data from one place to another place.In other words,
a stream is a path along which data flows
In Java, streams are the sequence of data that are read from the source and written to the
destination.
An input stream is used to read data from the source. And, an output stream is used to write
data to the destination.
.
Types of Streams:
There are two basic types of streams defined by Java, called byte stream and character stream.
The byte stream classes provide a convenient means for handling input and output of bytes and
character streams provide a convenient means for handling input and output of characters.
NEC Page 18
Character Stream Classes
Character streams can be used to read and write 16-bit Unicode characters. There are two kinds of
character stream classes, namely, reader stream classes and writer stream classes.
There are two kinds of Character Stream classes - Reader classes and Writer classes.
Reader Classes - These classes are subclasses of an abstract class, Reader and they
are used to read characters from a source(file, memory or console).
Writer Classes - These classes are subclasses of an abstract class, Writer and they
used to write characters to a destination(file, memory or console).
These two abstract classes have several concrete classes that handle unicode character.
NEC Page 19
FileReader Input stream that reads from file.
These classes define several key methods. Two most important are
1. read() : reads character data from the file.
2. write() : Writes character data to the file
import java.io.*;
NEC Page 20
}
Output:
Data successfully written in the specified file
NEC Page 21
Output stream classes are derived from the base class “Outputstream” like InputStream, the
OutputStream is an abstract class and therefore we cannot instantiate it. The several subclasses of
the OutputStream can be used for performing the output operations.
These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.
Stream class Description
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are
3. read() : reads byte of data.
4. write() : Writes byte of data
import java.io.*;
public class ByteDemo1
{
public static void main(String args[]) throws IOException
{
//Creating FileInputStream object
File file = new File("one.txt");
FileInputStream fis = new FileInputStream(file);
byte bytes[] = new byte[(int) file.length()];
NEC Page 22
File out = new File("two.txt");
FileOutputStream outputStream = new FileOutputStream(out,true);
Output:
Data successfully written in the specified file
Java - RandomAccessFile
Java RandomAccessFile provides the facility to read and write data to a file.
RandomAccessFile works with file as large array of bytes stored in the file system and a
cursor using which we can move the file pointer position.
In a sequential acces file only one mode of operation can take place either read only access
using Reader or InputStream classes and write only acces using Writer or OutputStream
classes.
A random-access file is a file that which allows for both reading and writing access by
using RandomAccessFile.
Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and
optionally to write to, the file specified by the File
argument.
RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and
optionally to write to, a file with the specified name.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously.
rws - Creates the file with read and write mode - synchronously.
NEC Page 23
S.No. Methods with Description
1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range 0-
255.
2 boolean readBoolean()
It reads a boolean value from from the file.
3 byte readByte()
It reads signed eight-bit value from file.
4 char readChar()
It reads a character value from file.
5 double readDouble()
It reads a double value from file.
6 int readInt()
It reads a integer value from file.
8 long length()
It returns the length of the file.
9 void write(int b)
It writes the specified byte to the file from the current cursor position.
10 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the file as a four-byte quantity, high byte
first.
11 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the file as an eight-byte quantity,
high byte first.
Example:
import java.io.*;
public class RandomIO {
public static void main(String[] args) throws IOException
{
// Create a random access file object.
RandomAccessFile file = new RandomAccessFile("myfile.dat", "rw");
NEC Page 24
// Writing to the file.
file.writeChar('S');
file.writeInt(2222);
file.writeDouble(222.22);
import java.io.*;
NEC Page 25
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String name = "";
try {
System.out.print("Please enter your name: ");
name = br.readLine();
System.out.println("Hello, " + name + "!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
br.close();
}
}
}
Output:
Please enter your name:NEC
Hello, NEC!
Reading input data using the Scanner class is the most commonly used method. This way of the
reading method is used by wrapping the System.in (standard input stream) which is wrapped in
a Scanner, we can read input from the console.
The Scanner class has defined in the java.util package.
Example
import java.util.Scanner;
public class ReadingDemo
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String name = "";
System.out.print("Please enter your name : ");
name = in.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Output:
NEC Page 26
Please enter your name:NEC
Hello, NEC!
import java.io.*;
public class ReadingDemo
{
public static void main(String[] args)
{
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
Output:
Please enter your name:NEC
Hello, NEC!
NEC Page 27
1. Writing console output using print() and println() methods
The PrintStream is a bult-in class that provides two methods print() and println() to write console
output. The print() and println() methods are the most widely used methods for console output.
Both print() and println() methods are used with System.out stream.
The print() method writes console output in the same line. This method can be used with console
output only.
The println() method writes console output in a separete line (new line). This method can be used
with console ans also with other output sources.
Example
}
}
Output:
01234
0
1
2
3
4
NEC Page 28
2. Writing console output using write() method
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.
Example
Output:
A
B
C
D
E
NEC Page 29
3 Process is heavyweight Thread is a lightweight process.
4 Each process has its own address in Threads share the same address space.
memory i.e. each process allocates
separate memory area.
7 A process does not have control over the Threads have control over the other threads
sibling process, it has control over its of the same process
child processes only.
Write a program to copy data from two files (merge two files) and write data into a third
file (using BufferedReader and PrintWriter classes)
import java.io.*;
if(line2 != null)
{
pw.println(line2);
line2 = br2.readLine();
NEC Page 30
}
}
pw.flush();
// closing resources
br1.close();
br2.close();
pw.close();
Write a JAVA program to display the number of characters, words, and lines in
a given file
import java.io.*;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
NEC Page 31
}
Output :
Number Of Characters in file : 86
Number Of Words in file : 14
Number Of Lines in file : 4
class FourThreadsDemo
{
public static void main(String args[])
{
FourThreads t1=new FourThreads("First Thread");
FourThreads t2=new FourThreads("Second Thread");
FourThreads t3=new FourThreads("Third Thread");
FourThreads t4=new FourThreads("Fourth Thread");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output:
NEC Page 32
Thread is :First Thread
Thread is :Second Thread
Thread is :Third Thread
Thread is :Fourth Thread
First Thread:1
Third Thread:1
Second Thread:1
Fourth Thread:1
Fourth Thread:2
First Thread:2
Third Thread:2
Second Thread:2
Fourth Thread:3
Third Thread:3
First Thread:3
Second Thread:3
NEC Page 33