Unit 5 Notes
Unit 5 Notes
String Handling in Java: Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings, Methods for Comparison of Strings, Methods for
Modifying Strings, Methods for Searching Strings, Data Conversion and Miscellaneous
Methods, Class String Buffer, Class String Builder.
Multithreaded Programming: Introduction, Need for Multiple Threads Multithreaded
Programming for Multi-core Processor, Thread Class, Main Thread, Creation of New Threads,
Thread States, Thread Priority, Synchronization, Deadlock and Race Situations, Inter-thread
Communication - Suspending, Resuming, and Stopping of Threads.
Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and
MySQL Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections,
ResultSet Interface, Creating JDBC Application, JDBC Batch Processing, JDBC Transaction
Management
Multithreaded Programming
Concept-1 Introduction
The process of executing multiple threads simultaneously is known as multithreading.
Thread is a lightweight unit of a process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
Multithreaded programs contain two or more threads that can run concurrently and each thread
defines a separate path of execution.
This means that a single program can perform two or more tasks simultaneously.
For example, one thread is writing content on a file at the same time another thread is
performing spelling check.
Process is the execution of a program that performs the actions specified in that program.
When program is loaded into the memory it automatically converting in to the process.
JAVA every program that we have been writing has at least one thread that is the MAIN
thread.
A Program starts executing the JVM is responsible for creating the main thread and calling the
main() Method.
Threads are executed by the processor according to the scheduling done by the java runtime
system by priority to every thread.
It simply means the higher priority as given preference for getting executed over the threads
having lower priority.
Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory.
Switching as well that helps to share the memory and reduce time of switching between
threads.
Multitasking
Multitasking is a process of performing multiple tasks simultaneously.
Computer system that perform multiple tasks like: writing data to a file, playing music,
downloading file from remote server at the same time.
Multitasking can be achieved either by using multiprocessing or multithreading.
Multitasking by using multiprocessing involves multiple processes to execute multiple tasks
simultaneously whereas Multithreading involves multiple threads to execute multiple tasks.
Thread vs Process
Parameter Process Thread
Definition Process means a program is in execution. Thread means a segment of a process.
Lightweight The process is not Lightweight. Threads are Lightweight.
Termination
The process takes more time to terminate. The thread takes less time to terminate.
time
Creation time It takes more time for creation. It takes less time for creation.
Communication between threads
Communication between processes needs
Communication requires less time compared to
more time compared to thread.
processes.
Context
It takes more time for context switching. It takes less time for context switching.
switching time
Resource Process consumes more resources. Thread consumes fewer resources.
Memory The process is mostly isolated. Threads share memory.
Sharing It does not share data Threads share data with each other.
Concept-2 Need for Multiple Threads & Multithreaded Programming for Multi-core Processor
To increase in throughput of computer is possible only by dividing the program into segments that are data
dependent and can be processed simultaneously by more than one processor. Thus, it decreases the total time
of computation.
This is the basis on which supercomputers are built.
In a supercomputer, thousands of processors are employed to concurrently process the data.
Hardware developers have gone a step further by placing more than one core processor in the same CPU chip.
Thus, now, we have multi-core CPUs.
Multithreaded Programming for Multi-core Processor
A CPU may have two cores - dual core or four cores - quad, six cores, or more.
CPUs having as many as 50 cores have also been developed. Moreover, computers with multi-core CPU are
affordable and have become part of common man's desktop computer.
Advancements in hardware are forcing the development of suitable software for optimal utilization of the
processor capacity. Multithread processing is the solution.
Multithread programming is inbuilt in Java and CPU capacity utilization may be improved by having multiple
threads that concurrently execute different parts of a program.
Concept-3 Thread life cycle or Thread States
Define a Thread:
Thread is a lightweight unit of a small process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
When program is load in to the main memory it is automatically converted as process.
Thread has its life cycle that includes various phases like: new, running, runnable, blocked, terminated etc.
Thread life cycle
New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on
it.
Runnable: After invocation of start() method on new thread, the thread becomes runnable.
Running: A thread is in running state if the thread scheduler has selected it.
Waiting: A thread is in waiting state if it waits for another thread to perform a task. In this stage the thread is
still alive.
Terminated: A thread enter the terminated state when it complete its task.
Daemon Thread
Daemon threads are a low priority thread that provides supports to user threads.
These threads can be user defined and system defined as well.
Garbage collection thread is one of the system generated daemon thread that runs in background.
These threads run in the background to perform tasks such as garbage collection.
Daemon thread does allow JVM from existing until all the threads finish their execution.
Concept-4 Creation of New Threads
Create a thread by instantiating or creating an object of type Thread class.
Java defines two ways in which this can be accomplished
1. By implementing the Runnable interface.
2. By extending the Thread class.
By extending the Thread class
This is the way to create a thread by a new class that extends Thread class and create an instance of
that class.
The extending class must override run() method which is the entry point of new thread.
Create the thread object and use the start() method to initiate the thread execution.
Declaring a class: Any new class can be declared to extends the thread class, thus inheriting all the
functionalities of the Thread class.
Class NewThread extends Thread {
------
------
}
Overriding the run() Method: The run() Method has to be overridden by writing codes required for the
thread. Specify the code that your thread will execute inside run() method.
Starting New Thread: The Start() Method which is required to create and initiate an instance of our Thread
class. NewThread thread1=new NewThread();
thread1.start();
The first line creates an instance of the class NewThread, where the object is just created. The thread is in
newborn state.
Second line which calls the start() method, moves the thread to runnable state, where the JVM will schedule
the thread to run by invoking the run() method. Now the thread is said to be in running state.
Program:
Methods Description
static Thread currentThread() Returns a reference to the currently executing thread
static int activeCount() Returns the current number of active threads
long getID() Returns the identification of thread
final String getName() Returns the thread’s name
final void join() Wait for a thread to terminate
void run() Entry point for the thread
final void setDaemon(boolean how) If how is true, the invoking thread is set to daemon status.
final boolean isDaemon() Returns true if the invoking thread is a daemon thread
final boolean isAlive() Returns boolean value stating whether a thread is still running
void interrupt() Interrupts a thread
Thread.State getState() Returns the current state of the thread
final int getPriority() Returns the priority of the thread
static boolean interrupted() Returns true if the invoking thread has been interrupted
final void setName(String thrdName) Sets a thread’s name to thrdName.
final void setPriority(int newPriority) Sets a thread’s priority to new priority
static void sleep(long milliseconds) Suspend a threads for a specified period of milliseconds
void start() Start a thread by calling its run() Method.
void destroy() Destroy the thread
Cause the current executing thread to pause and allow the other
static void yield()
threads to execute
Constructors of Thread Class
Constructors Description
It has no arguments, which simply means it uses the default name
Thread()
and the thread group
Thread(String threadName) The name of the thread can be specified as in threadName
Thread(ThreadGroup threadGroup,
Can specify the thread group and thread name.
String threadName)
Thread(Runnable threadOb, String ThreadOb is an instance of a class that implements the Runnable
threadName) interface.
By implementing the Runnable interface
Java Runnable is an interface used to execute code on a concurrent thread.
It is an interface which is implemented by any class, that the instances of that class should be executed by a
thread class.
The Runnable interface has an undefined method run() with void as return type, and it takes in no arguments.
This interface is present in java.lang package.
Method Description
This method takes in no arguments. When the object of a class implementing Runnable
public void run() interface is used to create a thread, then the run method is invoked in the thread which
executes separately.
Runnable interface is when we want only to override the run method.
When a thread is started by the object of any class which is implementing Runnable, then it invokes the run
method in the separately executing thread.
The class that implements Runnable, you will instantiate an object of type Thread from that class.
Thread defines several constructors
Thread(Runnable threadOb, String threadName)
ThreadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin.
The name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start() method, which is declared
within Thread class.
Program:
Concept-5 Thread Priority
Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
higher-priority threads get more CPU time than lower-priority threads.
A higher-priority thread can also preempt a lower-priority one when a lower-priority thread is running and a
higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-
priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a method of Thread class.
This is its general form: final void setPriority(int level)
level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
These priorities are defined as static final variables within Thread class.
To obtain the current priority setting by calling the getPriority( ) method of Thread final int getPriority( ).
Program:
Concept-6 Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
The synchronization is mainly used to
1. To prevent thread interference. 2. To prevent inconsistency problem.
Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it.
There are two types of thread synchronization
1. Synchronized method. 2. Synchronized block.
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.
Program: Output
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource 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.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Program: Output
Concept-7 Inter-thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Inter-thread communication is a mechanism in which a thread gets into wait state until another thread sends a
notification.
It is implemented by following methods
wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened.
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Concept-8 String Handling in Java: Introduction & String Class
A String is a sequence of character such as “abcdef” or “bell”.
In Java, a String is an object representing a sequence of characters.
In Java, a string is an object of a class, and there is no automatic appending of null character
by the system.
In Java, there are three classes that we can create strings and process them with methods.
(i) class String (ii) class StringBuffer (iii) class StringBuilder
All the three classes are part of java.lang package.
All the three classes have several constructors that can be used for constructing strings.
In the case of String class, an object may be created as String str1 = "abcd";
Here: String is a Predefined class of java.lang package str1 is an object not a variable. "abcd" is string literal
Program:
Output:
Output:
Concept-10 Methods for Extracting Characters from Strings
Method Description
char charAt(int index) It is used to extract a single character at an index
void getChars(int stringStart, int
It is used to extract more than one character
stringEnd, char arr[], int arrStart)
It is used extract characters from String object and then convert the
byte [] getBytes()
characters in a byte array
It is used to convert all the characters in a String object into an array of
char [] toCharArray()
characters.
int length() It is used extract the length of the string
Program:
Output:
Output:
Concept-13 Methods for Searching Strings
Method Description
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int
Returns the index within this string of the first occurrence of the specified character,
fromIndex) starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str,
Returns the index within this string of the first occurrence of the specified substring,
int fromIndex) starting at the specified index.
Program:
Output: