0% found this document useful (0 votes)
3 views

Day 5-Java-java.util package & Multithreading

Java-java.util package & Multithreading

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Day 5-Java-java.util package & Multithreading

Java-java.util package & Multithreading

Uploaded by

77rccbgkqb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Deloitte

Training
2016

FOUNDATION TRAINING
Java packages util and io,
overview of Multithreading 1
Deloitte Training 2016

Java
Day 5

3
Objectives of Day 5 Deloitte Training 2016

At the end of this module, you will be able to:


 Define a thread

 Manage and set thread priorities

 Use input-output mechanism of Java.

 Describe Java streams

 Write console based input – output programs in Java

 Define Serialization

 Utilize various classes in java.util

 List the different packages of Java

 Explain the classes and methods in each package

4
Multithreading Deloitte Training 2016

 What is … ?
 Multitasking
 Multiprocessing

 Multithreading

 Multitasking is the ability to run one or more programs


concurrently.
 Operating system controls the way in which these programs
run by scheduling them.
 Time elapsed between switching of programs is minuscule.
 Multithreading is the ability to execute different parts of a
program, called threads, simultaneously.

5
Thread Deloitte Training 2016
 Thread is the smallest unit of executable code that performs
a particular task.
 An application can be divided into multiple tasks and each
task can be assigned to a thread.
 Many threads executing simultaneously is termed as
Multithreading.

6
Benefits of Multithreading Deloitte Training 2016

 Multithreading requires less overhead than multitasking.


 In multitasking, processes run in their own different address
space.
 Tasks involved in multithreading can share the same address
space.
 Inter-process calling involves more overhead than inter-thread
communication.
 Multithreading allows us to write efficient programs that make
maximum use of the CPU.
 Multithreading allows animation loops to sleep for a second
between each frame without causing the whole system to pause.

7
Applications of thread Deloitte Training 2016

 Playing Applications
sound and of displaying
thread images
simultaneously.

 Displaying multiple images on the screen.


 Displaying scrolling text patterns or images on
the screen.

8
The ‘main’ thread Deloitte Training 2016

 When Java programs execute, there is always one thread


running and that is the main thread.
 It is this thread from which child threads are created.

 Program is terminated when main thread stops execution.

 Main thread can be controlled through Thread objects.

 Reference of the main thread can be obtained by calling the


currentThread() method of the Thread class.

9
contd..
 Two ways to create threads –
 Extend the Thread class

 Implement the Runnable interface

 The constructors of Thread class are –

1. Thread()
2. Thread(String threadName)
3. Thread(Runnable threadob)
4. Thread(Runnable threadob, String threadName)
5. Thread(ThreadGroup groupObj, Runnable threadob)
6. Thread(ThreadGroup groupObj, Runnable threadob, String
threadName)
Note : groupObj is the thread group to which new thread will
belong; default is the group of parent thread. If thread name is
not specified, JVM gives a name.
contd..
 Execution sequence class th extends Thread
 main is the calling thread {
from which all child th()
threads (thread objects) are { start() }
created or declared and
public void run()
called. { }
 Threads are initialized in }
the child class constructor
by the method start().
 start() invokes run(). The class samp
thread code is {
implemented in the run(). public static void main(String a[])
{ th obj1 = new th();
 Reordering
th obj2 = new th();
} }
Thread States
 Born: A newly created
Thread thread
States 3-1 is in a born state.

 Ready: After a thread is created, it is in its ready


state waiting for start() method to be called.

 Running: Thread enters the running state


when it starts executing.

 Sleeping: Execution of a thread can be halted


temporarily by using sleep() method. The
thread becomes ready after sleep time expires.
contd.. Deloitte Training 2016

 Waiting: Thread is in waiting


Thread States 3-3 state if wait()
method has been invoked. Used when two or
more threads run concurrently.

 Blocked: The thread enters a blocked state when


it waits for an event such as Input/Output
operations.

 Dead: The thread enters the dead state after the


run() method has finished or the thread’s stop()
method is called.

13
Different Stages in the Life of a Thread Deloitte Training 2016

New Thread
(BORN)

READY

SLEEPING SUSPENDED

RUNNING

WAITING BLOCKED

DEAD

14
Conditions that Prevent Deloitte Training 2016

Thread Execution
 Thread execution is interrupted if:
 Not of highest priority.

 Put to sleep using sleep() method.

 Is waiting because wait() method was called.

 Explicitly yielded using yield() method.

 Blocked for file I/O.

15
Managing Thread Priorities Deloitte Training 2016

 Priorities for carrying out activities changes at times.


 Similarly while programming, we may have to run a thread of
higher importance without stopping or suspending the current
running thread.
 Thread priorities play an important role in such a situation.
 Thread priorities in Java are constants defined in the Thread class.
 NORM_PRIORITY – value is
 MAX_PRIORITY – value is
 MIN_PRIORITY – value is
 The default priority is NORM_PRIORITY
 Two methods used to change priority:
 final void setPriority(int newp): changes the thread’s current priority.
 final int getPriority(): returns the thread’s priority.
16
Thread Synchronization Deloitte Training 2016
 At times, two or more threads may try to access a resource at the same
time, eg. one thread might try to read data from a file while the other
tries to change the data in the same file.
 In such a case, data may become inconsistent.
 To ensure that a shared resource is used by only one thread at any
point of time, we use synchronization.
 Synchronization is based on the concept of monitor.
 A monitor is an object that is used as a mutually exclusive lock.
 Only one thread can enter a monitor.
 When one thread enters the monitor, it means that the thread has
acquired a lock and all other threads must wait till that thread exits
the monitor. The programmer must invoke a method created using
the synchronized keyword.
 Owner of the method has to exit from the method to give
up control.
17
Synchronizing Code Deloitte Training 2016
 No explicit class called Monitor in Java. Each object has its own
implicit monitor that is entered when any of the object’s implicit
methods are called.
 If a thread is executing within the synchronized method of an object,
any other thread or synchronized method that tries to call that object
would have to wait.
 The owner (thread) of the monitor has to exit the monitor to give up
control of the monitor to the next thread waiting in the queue.
 If synchronized keyword is omitted, all the threads can simultaneously
invoke the same method, on the same object.
 This condition is known as race condition.
 Race conditions in a program are possible when:
 Two or more threads share data.
 They are reading and writing the shared data
simultaneously.

18
Synchronized Block Deloitte Training 2016

 It is not always possible to achieve synchronization by creating


synchronized methods within classes.
 We can put all calls to the methods defined by this class inside a
synchronized block.
 A synchronized block ensures that a method can be invoked only
after the current thread has successfully entered object’s monitor.
 The example shown earlier can be modified with the synchronized
keyword used in the method run() of the class ‘One’.

19
Input-Output in Java
Java performs I/O through streams.
 Stream is an abstraction that either produces information
or consumes information.
 Streams are connected to physical device by Java I/O
system.
 Input stream can abstract many different kinds of input –
keyboard, disk, network socket. Output stream can refer to
console, disk, network connection.
 Java implements streams within class hierarchies defined in
the java.io package.
contd..
Java Streams

Byte Stream Character Stream

Used for writing Used for writing and


and reading binary reading characters.
data. At lower level Can be inter–
all I–O is in binary nationalized as they
form. use Unicode.
contd..
Java Streams

Byte Stream Character Stream

InputStream OutputStream Reader Writer

read() write() read() write()


contd..
 Stream Classes – The entire Java I/O is based upon four
abstract classes viz.. InputStream, OutputStream, (byte
stream) Reader, Writer (character stream).
 Character stream classes are used when working with
characters or strings. Byte stream classes are used when
working with bytes or other binary objects.
 Byte Stream classes cannot work directly with Unicode
characters.
 Java supports direct I/O support for characters keeping in
tune with “write once, run anywhere” philosophy.
Byte Stream
 InputStream – defines the following methods
 int read() – Returns an integer representation of next
available byte of input. At end of file, it returns -1.
 int read(byte buffer[]) – Returns the actual number of
bytes that were successfully read. -1is returned when end
of file is encountered.
 int read(byte buffer[]. int offset, int numBytes) –
Returns number of bytes successfully read, -1 is returned
when endof file is encountered.
contd..
 OutputStream – defines the following methods
 int write(int b) – Writes a single byte to an outputstream.
 int write(byte buffer[]) – Writes a complete array of bytes
to an output stream.
 int write(byte buffer[], int offset, int numBytes) – Writes
a subrange of numbytes from arraybuffer beginning at
buffer[offset].
contd..
 PrintStream – the class provides all of the formatting
capabilities The two constructors are –
 PrintStream(OutputStream outputStream)
 PrintStream(OutputStream outputStream, boolean
flushOnNewline)
 where flushOnNewline controls whether Java flushes the
output stream every time a newline (\n) character is output.
 if flushOnNewline is true, flushing automatically takes
place. If it is false, flushing is not automatic. The first
constructor does not automatically flush.
Console Input-Output
 The System class contains three predefined stream variables
in, out and err. These fields are declared as public and static.
 System.out refers to standard output stream; out is the
object of type PrintStream.
 System.in refers to standard input stream; in is the object
of type InputStream;
 System.err refers to standard error stream; its an object of
type PrintStream.
 Classes and their purpose :
 BufferedReader – Buffered input character stream.
 BufferedWriter – Buffered output character stream.
 InputStreamReader – Input stream that translates bytes
to characters.
contd..
 Console input is done using System.in.
 System.in is wrapped in a BufferedReader object.
 BufferedReader(Reader inputreader);
where inputreader is the stream linked to instance of
BufferedReader ;
 InputStreamReader is one of the concrete subclass of
Reader ;
 The following constructor is used to obtain an ISR object
linked to System.in
InputStreamReader(InputStream inputstream)
contd..
 Summarizing the above,
 BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
 br is a character based stream that is linked to the console
through System.in.
 console output is achieved through print() and println(),
the methods are defined by the class PrintStream.
 PrintStream also implements a method write().
 write(int byteval)
 Usage :
 void System.out.write();
Character Streams
 BufferedReader – the class improves performance by
buffering input. It defines the following constructors:
 BufferedReader(Reader inputStream)
- creates a buffered character stream using a default buffer
size.
 BufferedReader(Reader inputStream, int bufSize)
- the size of the buffer is passed in bufSize.
contd..
 BufferedWriter – is a writer class that adds a flush( )
method and can be used to ensure that data buffers are
physically written to the actual output stream.
 BufferedWriter increases performance by reducing the
number of times data is actually physically written to the
output stream.
 BufferedWriter has two constructors :
o BufferedWriter(Writer outputStream) it creates a
buffered stream using a buffer with a default size.
o BufferedWriter(Writer outputStream, int bufSize) in this
the size of the buffer is passed in bufSize.
contd..
 PrintWriter - the class provides for formatted output
methods print( ) and println( ).
 PrintWriter has four constructors:
 PrintWriter(OutputStream outputStream)
 PrintWriter(OutputStream outputStream, boolean
flushOnNewline)
 PrintWriter(Writer outputStream)
 PrintWriter(Writer outputStream, boolean flushOnNewline)
o where flushOnNewline controls whether Java flushes
the output stream every time println( ) is called. If
flushOnNewline is true, flushing automatically takes
place.
o If false, flushing is not automatic. The first and third
constructors do not automatically flush.
File
 File – File class directly deals with files and file system, but
not through streams.
 File object is used to obtain or manipulate the
information associated with the disk file, such as
permissions, time, date, directory path and navigate sub
directory hierarchies.
 Constructors of File class –
o File(String directorypath)
o File(String directorypath, String filename)
o File(String dirobj, String filename)
o File(URI uriobj)
 Directorypath – is the path name of the file, filename is
the name of the file, dirobj is File object that describes a
directory, uriObj is URI object that describes a file.
contd..
 Methods –
 boolean isFile() – returns true if called on a file and false if
called on a directory, device drivers, named pipes.
 boolean isAbsolute() – returns true if the file has an
absolute path and false if the path is relative.
 boolean renameTo(File newName) – renames the file
specified by invoking object with newName .
 boolean delete() – deletes the disk file represented by the
path of the invoking File object. Can also delete directory if
its empty.
contd..
 Directory – A directory is a File that contains a list of other
files and directories.
 isDirectory() method returns true on a File object when the
object in question is Directory.
 list() is invoked to extract the list of files and directories.
File Streams
 FileOutputStream – creates an OutputStream used to write
bytes to a file. The constructors of FOS are -
 FileOutputStream(String filePath)
 FileOutputStream(File fileObj)
 FileOutputStream(String filePath, boolean append)
 FileOutputStream(File fileObj, boolean append)
 FileInputStream - creates an InputStream that is used to
read bytes from a file. The constructors of FIS are
 FileInputStream(String filepath)
 FileInputStream(File fileObj)
√ The filepath is the full path name of a file, and fileObj is
a File object that describes the file.
 Objects of FIS throw FileNotFoundException.
contd..
 FileReader – the class creates a Reader that is used to read
the contents of a file. It defines following constructors –
 FileReader(String filePath)
 FileReader(File fileObj)
 filePath is the full path name of a file, and fileObj is a
File object that describes the file.
 FileWriter – the class that creates is used to write to a file.
It defines following constructors –
 FileWriter(String filePath)
 FileWriter(String filePath, boolean append)
 FileWriter(File fileObj)
 FileWriter(File fileObj, boolean append)
contd..
 RandomAccessFile the class encapsulates a random-access
file.
 It implements the interfaces DataInput and DataOutput
which define the basic I/O methods.
 It also supports positioning requests — the file pointer
within the file can be positioned.
 The class has these two constructors:
o RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
o RandomAccessFile(String filename, String access)
throws FileNotFoundException
Note - It is not derived from InputStream or OutputStream.
contd..
 Methods of RandomAccess –
 seek( ) – used to set the current position of the file pointer
within the file:
 void seek(long newPos) throws IOException
 newPos specifies the new position, in bytes, of the file
pointer from the beginning of the file.
 After a call to seek( ), the next read or write operation will
occur at the new file position.
 setLength( ) – used to lengthen or shorten a file.
 void setLength(long len) throws IOException
 sets the length of the invoking file to that specified by len.
 Note – If the file is lengthened, the added portion is
undefined.
contd..
 Serialization – it is the process of writing the state of an
object to a byte stream.
 Applied in situations to save the state of the object to a
persistent storage area, such as a file. At a later time, the
state of these objects can be restored by using the process of
de-serialization.
 Serialization is used in implementing Remote Method
Invocation (RMI).
√ RMI allows a Java object on one machine to invoke a
method of a Java object on a different machine.
√ An object may be supplied as an argument to that
remote method.
√ The sending machine serializes the object and transmits
it. The receiving machine de-serializes it.
contd..
 Serializable – An interface which provides for
implementing serialization.
 The Serializable interface defines no members. It is
simply used to indicate that a class may be serialized.
 If a class is serializable, all of its subclasses are also
serializable.
 Variables that are declared as transient are not saved by
the serialization facilities.
 Variables that are declared static variables are not saved.
contd..
 ObjectOutput – The ObjectOutput interface extends the
DataOutput interface and supports object serialization. It
defines the writeObject( ) and other methods. writeObject( ) is
called to serialize an object. All of these methods will throw an
IOException on error conditions.

 ObjectOutputStream – The ObjectOutputStream class extends


the OutputStream class and implements the ObjectOutput
interface.
The constructor ObjectOutputStream(OutputStream outStream)
throws IOException The argument outStream is the output
stream to which serialized objects will be written.
The methods of this class throw an IOException on error
conditions.
contd..
 ObjectInput – The ObjectInput interface extends the
DataInput interface and defines the readObject( ) and various
methods. It supports object serialization.
This is called to deserialize an object.
All of these methods will throw an IOException on error
conditions. The readObject( ) method can also throw
ClassNotFoundException.
 ObjectInputStream – The ObjectInputStream class extends the
InputStream class and implements the ObjectInput interface.
ObjectInputStream is responsible for reading objects from a
stream. The constructor ObjectInputStream(InputStream
inStream) throws IOException
The argument inStream is the input stream from which serialized
objects should be read.Several methods of this class will throw an
IOException on error conditions. 43
Packages in Java Deloitte Training 2016

A package is a set of classes that are stored in a directory, which has


the same name as the package name. Packages enable you to organize
the class files provided by Java. The Java packages are classified into
the following two categories:
 Java Application Programming Interface (API) packages: The
Java API consists of various packages, such as java.lang, java.util,
java.io, java.awt, java.net, and java.applet.
 Java user-defined packages: The packages that a user creates are
called user-defined packages. The user-defined packages can be
imported in any Java program.

44
Java Packages Deloitte Training 2016
The following table lists a few built–in Java packages.
Java Package Name Description
java.lang Provides various classes, such as Object, System, and Class.
java.util Provides various classes that support collection or groups of
objects, such as hash tables, string parsing, and system properties.
java.io Defines two streams, input stream and output stream that
determine the flow of bytes from a source to destination.
java.awt Provides classes to implement graphical user interface, such as
creating buttons, check boxes, text boxes, menus, and list boxes.
java.net Provides classes that support network programming, such as
Socket, ServerSocket, and DatagramSocket.
java.applet Provides the Applet class that provides methods to display
images, play audio files, and obtain information about the applet
environment. Some of these methods are play(), getImage(),
getAppletInfo(), and getAudioClip().

45
import Statement Deloitte Training 2016

 The import statement is used to include a Java package in a


program. The following syntax shows how to import a package in
a Java program:
 import<package_name>.*;

 import<package_name>.<class_name>;

 The following syntax shows how to import the awt package in a


Java program:
 import java.awt. *; // Imports all the classes of the awt
package
 import java.awt.Button; // Imports only the Button class
of the awt //package

46
java.lang Deloitte Training 2016
 The java.lang package provides various classes and interfaces that are
fundamental to Java programming.
Class Description
Object All the classes in the java.lang package are subclasses of the Object class and
inherit its methods.
Class Supports runtime processing of the class information of an object. The Class
class also supports the toString() method.
System Provides a standard interface to input, output, and error devices, such as
keyboard and Visual Display Unit (VDU).
Wrapper Represents the primitive data types, such as int, char, and double, as objects.
Character Provides methods for determining the type of character and converting
characters from uppercase to lowercase, and vice-versa.
Integer Provides methods for converting an int object to a String object.
Math Provides various numeric constants and methods for statistics, logarithms,
exponents, and trigonometry.
String Supports operations on strings and characters.
Enum Operates as the base class of all Java language enumeration types.

47
java.util Deloitte Training 2016
 The java.util package provides various utility classes and interfaces that
support date/calendar operations, string manipulation, parsing, and
basic event processing.
Class Description
BitSet Creates a set of bits that grows as required.
Date Encapsulates date and time information.
Hashtable Implements a hash table, which maps keys to values.
Random Generates a stream of random numbers.
StringTokenizer Provides methods to break a string into tokens.
Scanner Scans primitive data types and strings by using regular
expressions, and then breaks then into tokens.
Arrays Provides various methods to perform various operations on
arrays, such as searching and sorting.
Calendar Provides support for date conversion and can be extended
to provide conversion for specific calendar systems.
GregorianCalendar Provides the standard calendar used worldwide. It is a
subclass of the Calendar class.
48
contd..
 java.util package contains powerful classes and interfaces
which provide for extra utility.
 Classes of java.util
 StringTokenizer
 Date
 Calender
 Random
 Scanner
 Currency
 EventObject
contd..
 StringTokenizer –
 StringTokenizer provides the lexer (or scanner) i.e. the first step in
parsing process.
 StringTokenizer implements the Enumeration. Hence, an input
string can be enumerated as the individual tokens contained in it
using StringTokenizer.
 Constructors of StringTokenizer
 StringTokenizer(String str)
 StringTokenizer(String str, String delimiters)
 StringTokenizer(String str, String delimiters, boolean delimAsToken)
Note : The processing of text often consists of parsing a
formatted input string. Parsing is the division of text into a set of
discrete parts, or tokens, which in a certain sequence can convey a
semantic meaning.
contd..
 Methods of StringTokenizer –
 int countTokens() – determines the number of tokens left
to be parsed and returns that number.
 boolean hasMoreElements() – Returns true if one or more
tokens remain in String and false otherwise
 boolean hasMoreTokens() – Returns true if one or more
tokens remain in String and false otherwise
 Object nextElement() – Returns next token as an Object.
 String nextToken() – Returns the next token as a String.
 String nextToken(String delimiters) – Returns the next
token as a String and sets the delimiters string to that
specified by delimiters.
contd..
 Date class
 Encapsulates the current date and time.
 Constructors of Date class
 Date()
 Date(long millisec)
 Most of the methods are deprecated and moved to the
classes Calendar and DateFormat.
contd..
 Calendar class –
 An abstract class that provides for converting time in
milliseconds into a number of useful components viz..
year, month, day, hour, minute and second.
 Calendar class has no constructors
 Methods of Calendar class
 abstract void add(int w, int v)
 boolean after(Object calObj)
 boolean before(Object calObj)
 final void clear()
 Calendar defines some int constants, which are used with
get or set components of the calendar.
contd..
Scanner class
 Scanner reads formatted input and converts it into its
binary form.
 Scanner can be used to read input from the console, a file,
a String, or any source that implements the Readable
interface or ReadableByteChannel.
 To use Scanner, the procedure is :
1. Determine if a specific type of input is available by calling one of
Scanner’s hasNextX methods, where X is the datatype
2. If input is available, read it by calling one of Scanner’s nextX
methods.
3. Repeat the process until input is exhausted.
 Scanner defines two sets of methods to read input.
The Enumeration Interface Deloitte Training 2016

 The Enumeration interface defines the methods by which you


can enumerate or obtain the elements in a collection of
objects.
 This interface provides two methods: hashMoreElements()
and nextElement().
 The hashMoreElements() method enables you to determine
elements that are contained in an Enumeration object.
 The nextElement() method returns the nextElement() if one
more element is contained by an object.

55
Legacy Classes and Interfaces Deloitte Training 2016

The various legacy classes defined by the java.util package are:


 Vector

The Vector class implements a dynamic array of objects.


 Stack

The Stack class provides the capability to create and use


storage objects called stacks within your Java programs.
 Hashtable

The Hashtable class implements a hash table data structure.


 Properties

The Properties class is a subclass of Hashtable that can be read


or written from a stream.

56
java.util.regex Deloitte Training 2016

 The java.util.regex package enables you to create a Java program


that manipulates regular expressions.
 A regular expression is a sequence of characters that specify
search pattern for a string.
 The java.util.regex package consists of the following classes to
manipulate the regular expressions:
 Pattern – Pattern class is used to create and compile a regular
expression.
 Matcher – The Matcher class is used to match character
sequences against a given string sequence pattern.
 Formatter – The Formatter class of the java.util package
enables you to create a Java program that generates formatted
output.

57
java.text Deloitte Training 2016

 The java.text package provides classes and interfaces for creating


programs that formats and parses dates, numbers, and text in a
language-independent manner.
 Formatting date or number means converting these to a string
in a particular format, whereas, parsing means converting a
string to a date or number.
 The java.text package consists of the following classes for
formatting and parsing dates, numbers, and text:
 DateFormat : It provides methods for formatting and parsing
dates.
 NumberFormat : It provides methods for formatting and
parsing numbers and currency values.

58
Summary Deloitte Training 2016

 You have learned how to:


 Use java streams
 Handle console based input-output
 Serialize the objects.
 List the different packages of Java
 Explain the classes and methods in each package
 Write programs using the packages
 Define multithreading
 List benefits of multithreading
 Discuss thread states
 Manage thread priorities
 Explain how to set thread priorities
 Explain thread synchronization

59

You might also like