You are on page 1of 33

MODULE - V

MultiThreading
“Multithreading in java is a process of executing multiple threads simultaneously.”
Multiprocessing and multithreading, both are used to achieve multitasking.
What is Thread?

 A thread is a single sequential flow of control within a program.


 A thread is a lightweight sub-process, the smallest unit of processing.
 Multithreading in Java is a process of executing multiple threads simultaneously.
 Multithreading 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.
 It differs from a “process” in that a process is a program executing in its own address space
whereas a thread is a single stream of execution within a process.
 Java Multithreading is mostly used in games, animation, etc.

What is Multithreading in Java?


Multithreading in Java is a process of executing two or more threads simultaneously to maximum
utilization of CPU. Multithreaded applications execute two or more threads run concurrently.
Hence, it is also known as Concurrency in Java. Mulitple threads don't allocate separate memory
area, hence they save memory. Also, context switching between threads takes less time.
A program that contains multiple flows of control is known as multithreaded program

Advantages of Java Multithreading

 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 Thread Model:

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.

3. Thread Life Cycle:

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

A thread can be preempted by a higher-priority thread: In this case, a lower-priority thread


that does not yield the processor is simply preempted—no matter what it is doing— by a higher-
priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called
preemptive multitasking.

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.

The synchronization is mainly used to a) To prevent thread interference b) To prevent data


inconsistency problem.

Synchronization can be done by two ways:

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.

7. The Thread Class and the Runnable Interface

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.

Thread Life cycle (or) Thread States :


A thread goes through various stages in its life cycle.
Thread has following states:
 Newborn
 Runnable
 Running

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.

The Main Thread:


When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.

The main thread is important for two reasons:

 It is the thread from which other “child” threads will be spawned.


 Often, it must be the last thread to finish execution because it performs various shutdown
actions.

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:

// Controlling the main Thread.


class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
for(int i = 0; i < 5; i++)
{
System.out.print(i +" ");
Thread.sleep(1000);
}

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.

In the line, Current thread: Thread [main, 5, main],


[main, 5, main] tells about [the name of the thread, its priority, and the name of its group]

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( )

getName( ): The getName() method is used to get the name of a thread.


final void setName(String threadName)

Thread Class:

 Java’s multithreading system is built upon the Thread class.


 Thread encapsulates a thread of execution.
 Thread class provide constructors and methods to create and perform operations on
a thread.

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.

Commonly used Constructors of Thread class:


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

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.

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

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( )

 It has to call start( ) to begin execution of the new thread.

Example: program to extend Thread


class A extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
A t=new A();
t.start();
}
}

Output: thread is running...

2. By implementing Runnable interface.

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

Create multiple threads


The program to create multiple threads using Extending Thread class:

class A extends Thread


{
public void run()
{
try
{
for(int i=1;i<=3;i++)
{
System.out.println(“A - ”+i);
Thread.sleep(1000); // thread to sleep for 1 second
}
}
catch(InterruptedException ie)
{
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int i=1;i<=3;i++)
{
System.out.println(“B - ”+i);
Thread.sleep(2000); // thread to sleep for 2 seconds
}
}
catch(InterruptedException ie){}
}
}
class Thread1
{
public static void main(String args[])
{
NEC Page 9
A t1=new A();
B t2=new B();
t1.start();
t2.start();

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:

public final void join() throws InterruptedException


public final void join(long milliseconds) throws InterruptedExceptin
public final void join(long milliseconds, int nanoseconds) throws InterruptedExceptin

Example-1

class MyThread extends Thread


{
public void run()
{
for (int j = 0; j < 5; j++)
{
System.out.println("child thread");
try { Thread.sleep(2000); }
catch(InterruptedException e) { }
}
}
}
public class ThreadJoinDemo1
{
public static void main (String argvs[]) throws InterruptedException
{
MyThread t = new MyThread();
NEC Page 11
t.start();
t.join();

for (int j = 0; j < 5; j++)


{
System.out.println("main thread");
}
}
}

Output:

child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread

Naming Thread and Current 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:

1. public String getName(): is used to return the name of a thread.


2. public void setName(String name): is used to change the name of a thread.

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.

There are 3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. 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.

Let us do discuss how to get and set priority of a thread in java.


setPriority( ) :
The java.lang.Thread.setPriority() method updates or assign the priority of the
thread to newPriority.

Syntax: public final void setPriority(int newPriority)

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");
}
}
}

public class ThreadPriorityDemo


{
public static void main (String argvs[]) throws InterruptedException
{
MyThread t = new MyThread();
t.setPriority(10);
t.start();

for (int j = 0; j < 5; j++)


{
System.out.println("main thread");
}
}
}
Output:
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main 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.

Concept of Lock in Java

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

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Synchronization can be done by two ways:

1. synchronized block
2. synchronized method

NEC Page 15
synchronized method

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


 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.

Syntax:

Syntax:

<access modifier> synchronized method (parameter)


{
//synchronized code
}

In the case of the synchronized method, the lock object is:


1. class object – if the given method is static.
2. this object – if the method is non-static. ‘this’ is the reference to the current object in
which the synchronized method is invoked.

//example of java synchronized method

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);
}
}
}

class MyThread extends Thread


{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
NEC Page 16
}
public class SynchronizedDemo
{
public static void main (String argvs[])
{
Display d = new Display();
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
Output:
Good Morning : NEC
Good Morning : NEC
Good Morning : NEC
Good Morning : NEC
Good Morning : NEC
Good Morning : ECE
Good Morning : ECE
Good Morning : ECE
Good Morning : ECE
Good Morning : ECE

synchronized block

 Synchronized block can be used to perform synchronization on any specific resource(part)


of the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
 Scope of synchronized block is smaller than the method.
 Synchronized block is used to lock an object for any shared resource.
 The main advantage of synchronized block over synchronized method is that it reduces
waiting time of threads and improves performance of the system.

Syntax for 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);
}
}
}
}

Note: Remaining code is same as synchronized method example

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.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

NEC Page 19
FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

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

Example Reader/Writer Streams (Reading and writing Files)


Following Java program reads data from a particular file using FileReader and writes it to another,
using FileWriter.

import java.io.*;

public class CharacterIO


{
public static void main(String args[]) throws IOException
{
//Creating FileReader object
File file = new File("input.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];

//Reading data from the file


reader.read(chars);

//Writing data to another file


File out = new File("output.txt");
FileWriter writer = new FileWriter(out);

//Writing data to the file


writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}

NEC Page 20
}
Output:
Data successfully written in the specified file

Byte Stream Classes


Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes.

Java provides two kinds of byte stream classes:


 input stream classes and
 output stream classes

Input Stream Classes


Input stream classes that are used to read bytes include a super class known as “Inputstream” and a
number of subclasses for supporting various input-related functions. The super class InputStream
is an abstract class, and, therefore, we cannot create instances of this class. Rather, we must use
the subclasses that inherit from this class.

Output Stream Classes

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

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are
3. read() : reads byte of data.
4. write() : Writes byte of data

Example Input/Output Streams Reading and writing Files


Following Java program reads data from a particular file using FileInputStream and writes it to
another, using FileOutputStream.

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()];

//Reading data from the file


fis.read(bytes);

//Writing data to another file

NEC Page 22
File out = new File("two.txt");
FileOutputStream outputStream = new FileOutputStream(out,true);

//Writing data to the file


outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}

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.

The methods of RandomAccessFile class:

Some of the methods discussed here are:

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.

7 void seek(long pos)


It sets the file-pointer(cursor) measured from the beginning of the file, at which the
next read or write occurs.

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);

file.seek(0); // Moving file pointer to the beginning.

// Reading data from the file.


System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());

file.close(); // Closing stream.


}
}
S
2222
22.22

Console Input/Output Operations in Java

Reading console input in java


In java, there are three ways to read console input. Using the 3 following ways, we can read input
data from the console.

1. Using BufferedReader class


2. Using Scanner class
3. Using Console class

Let's explore the each method to read data with example.


1. Reading console input using BufferedReader class in java
Reading input data using the BufferedReader class is the traditional technique. This way of the
reading method is used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from the
console.
The BufferedReader class has defined in the java.io package.

Example - using BufferedReader class.

import java.io.*;

public class ReadingDemo


{
public static void main(String[] args) throws IOException
{

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!

2. Reading console input using Scanner class in java

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!

3. Reading console input using Console class in java


Reading input data using the Console class is the most commonly used method. This class was
introduced in Java 1.6 version.
The Console class has defined in the java.io package.
Example

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!

Writing console output in java


In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.

1. Using print() and println() methods


2. Using write() method

Let's explore the each method to write data with example.

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

public class WritingDemo


{
public static void main(String[] args)
{
int[] list = new int[5];
for(int i = 0; i < 5; i++)
list[i] = i;
for(int i:list)
System.out.print(i); //prints in same line
System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines

}
}

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

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[5];

for(int i = 0; i < 5; i++) {


list[i] = i + 65;
}
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}

Output:
A
B
C
D
E

Difference between Process and Thread:

S.NO Process Thread


1 A program in execution is often referred A thread is a path of execution in a
as process. program. A thread is a subset (part) of the
process.
2 Multi-processing is the feature that allows Multi-threading is a process of executing
to run two or more programs concurrently multiple threads (different parts of a
program/process) simultaneously

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.

5 Interprocess communication is expensive Interthread communication is inexpensive.


and limited
6 Context switching from one process to Context switching from one thread to other
another is high cost. is low cost.

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.*;

public class FileMerge


{
public static void main(String[] args) throws IOException
{
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter("file3.txt");

// BufferedReader object for file1.txt and file2.txt


BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));

String line1 = br1.readLine();


String line2 = br2.readLine();

// loop to copy lines of file1.txt and file2.txt to file3.txt


while (line1 != null || line2 !=null)
{
if(line1 != null)
{
pw.println(line1);
line1 = br1.readLine();
}

if(line2 != null)
{
pw.println(line2);
line2 = br2.readLine();

NEC Page 30
}
}

pw.flush();
// closing resources
br1.close();
br2.close();
pw.close();

System.out.println("Merged file1.txt and file2.txt into file3.txt");


}
}
Output:
Merged file1.txt and file2.txt into file3.txt

Write a JAVA program to display the number of characters, words, and lines in
a given file

import java.io.*;

public class WordCharLineCountInFile


{
public static void main(String[] args) throws IOException
{

int charCount = 0;
int wordCount = 0;
int lineCount = 0;

BufferedReader reader = new BufferedReader(new FileReader("test.txt"));


String currentLine = reader.readLine();
while (currentLine != null)
{
lineCount++;
String[] words = currentLine.split(" ");
wordCount = wordCount + words.length;

for (String word : words)


{
charCount = charCount + word.length();
}
currentLine = reader.readLine();
}
System.out.println("Number of character in file : "+charCount);
System.out.println("Number of words in a file : "+wordCount);
System.out.println("Number of lines in file : "+lineCount);
reader.close();
}

NEC Page 31
}

Output :
Number Of Characters in file : 86
Number Of Words in file : 14
Number Of Lines in file : 4

Write a program to create multiple threads in your program context switch


among the threads using sleep functions

class FourThreads extends Thread


{
FourThreads(String n)
{
super(n);
System.out.println("Thread is :"+getName());
}
public void run()
{
try
{
for(int i=1;i<=3;i++)
{
System.out.println(getName()+":"+i);
sleep(200);
}
}
catch(InterruptedException e)
{
System.out.println(getName()+"is Interrupted");
}
}
}

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

You might also like