Unit 4
Unit 4
HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032
1.1 MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form
of multitasking.
Multiprocessing and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time
than process. Java Multithreading is mostly used in games, animation, etc.
What is a Thread?
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
betweenthe threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
A process-based multitasking is the feature that allows our computer to run two or more
programs concurrently. For example, process-based multitasking enables us to run the Java
compiler at the same time that we are using a music player.
Each process has an address in memory. In other words, each process allocates a separate
memoryarea.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks simultaneously.
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and again
back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the
thread is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has
entered the critical section of a code and is not willing to leave that critical section. In such a scenario,
another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed
waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start
its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there
is no way one can respawn (active after kill) the dead thread.
1.3 THREAD PRIORITY
Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
Priorities are represented by a number between 1 and 10.
In most cases, thread schedular 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
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in whichthreads execute and very much platform dependent.
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 are simple:
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.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
Here, 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. You can obtain the current priority setting
by calling the getPriority() method of Thread, shown here:
final int getPriority( )
Program
class Main
{
public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t1.getState());
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
t1.setPriority(6);
t1.start();
t1.join();
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
System.out.println("State of the thread - " + t1.getState());
Thread t2 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t1 is : " + t2.getPriority());
t2.setPriority(9);
t2.start();
t2.join();
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t2 is : " + t2.getPriority());
}
}
Output
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
Priority of the thread t1 is : 6
State of the thread - TERMINATED
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
State of the thread – TERMINATED
Priority of the thread t2 is : 9
Method Meaning
Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new
Multi(); t1.start();
}
}
Output: thread is running...
To implement Runnable, a class need only implement a single method called run( ),
which is declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.
After we create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and 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. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new
Thread(obj); t1.start();
}
}
Output: thread is running...
import java.util.Scanner;
class MyThread1 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int nums[] = new int[n];
System.out.println("Enter " + n + " numbers");
for(int i = 0; i < n; i++)
{
nums[i] = in.nextInt();
}
}
}
class MyThread2 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Even numbers in the range 1 - " + n);
for(int i = 2; i <= n; i = i + 2)
System.out.println(i + " ");
}
}
new Thread()
{
public void run(){c.deposit(10000);}
}.start();
}
}
1.6 SYNCHRONIZATION
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object
that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting
to enter the locked monitor will be suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same
monitor if it so desires.
}
}
Output:
5
10
15
20
25
100
200
300
400
500
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
To use a class or a package from the library, you need to use the import keyword:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If a class want to be used from a package, for example, the Scanner class, which is used to get user input,
write the following code:
import java.util.Scanner;
User-defined packages
To create a package, include a package command as the first statement in a Java source file. Any
classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If the package statement
is omitted, the class names are put into the default package, which has no name.
While the default package is fine for short, sample programs, it is inadequate for real applications.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;
Example
package MyPack;
class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n; bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> "); JAVA LANGUAGE System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3]; current[0] = new Balance("Sanjib", 123.23); current[1] = new
Balance("Chandan", 157.02); current[2] = new Balance("Palak", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance
class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command, or to
have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is
now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot
use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
package MyPack;
public class Balance
{
String name; double bal;
public Balance(String n, double b)
{
name = n; bal = b;
}
public void show()
{
if(bal<0) System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are public,
too. This means that they can be accessed by any type of code outside the MyPack package. For example,
here TestBalance imports MyPack and is then able to make use of the Balance class:
1.10 COLLECTION
In general terms a collection is a “group of objects”
Collection is a container object. It is used for storing homogeneous and heterogeneous, unique and duplicate
objects without size limitation and further it is used for sending objects at a time from one class methods to
other class methods as method arguments and return type with single name across multiple layers of the project.
Utility Objects: it is nothing but a class that is given to perform different operations on container
objects are called utility objects i.e two classes
8. Collections class
9. Arrays
The Collection in Java is a framework that provides architecture to store and manipulate thegroup of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
searching,
sorting,
insertion,
manipulation,
deletion etc.
4. Java collection framework provide many Interfaces and classes
Collection Interfaces and class hierarchy
Iterable is the root interface of the Java collection classes. The Collection interface extends
Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface stands
to represent data-structures whose value can be traversed one by one. This is an important property.
Choosing the Right Collection
SETS:
A set represents a group of elements arranged just like an array. The set will grow dynamically when the
elements are stored into it. A set will not allow duplicate elements. If we try to pass for same element that is
already available in the set, then it is not stored into the set.
LIST:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be stored.
QUEUES:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that an element
that is stored as a first element into the queue will be removed first from the queue.
MAPS:
Maps store elements in the form of key and value pairs. If the key is provided then
it’scorrespond value can be obtained. Of course, the keys should have unique values.
In the hierarchy we can divided into two groups
1. If your requirement is to group key-value pair, then choose MAP
2. If your requirement (operations are on only values) is to have only the values, then choose
collection interfaces
for(variable : collection-object)
{
Statements:
}
Here, the variable assumes each element of the collection-object and the loop is executed as many times as there
are number of elements in the collection-object. If collection-object has n elements the loop is executed exactly
n times and the variable stores each element in each step.
Example using for-each loop
class ForEachDemo{
public static void main(String args[]){
int arr[] = {12,13,14,44}; //declaring an array for(int i : arr){
//traversing the array with for-each
loopSystem.out.println(i);
}
}
}
Output: 12
13
14
44
2. Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one by one
from a collection object. It retrieves elements only in forward direction. It has 3 methods:
3. ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements
from a collection object, both in forward and reverse directions. It can retrieve the elements in forward
and backward direction. It has the following important methods:
4. Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It
has 2 methods.
HashSet Class
HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the
order of elements. Also it does not allow the duplicate elements to be stored.
We can write the HashSet class as : class HashSet <T>
We can create the object as : HashSet <String> hs = new HashSet<String> ();
HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into the HashSet
initially. This capacity may increase automatically when more number of elements is being stored.
Program : Write a program which shows the use of HashSet and Iterator. package
com.myPack;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet <String> hs = new HashSet<String> ();
hs.add ("Anil"); hs.add ("Akshara");
hs.add ("Babji");
hs.add ("Charan");
hs.add ("Raman");
// hs.add("India");
System.out.println ("HashSet = " + hs);
Iterator<String> it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{
String s = (String) it.next ();
System.out.println(s);
}
}
}
Output:
HashSet = [Akshara, Raman, Babji, Anil, Charan]Elements Using Iterator: Akshara
Raman Babji
Anil Charan
Program on Hashset
LinkedHashSet Class
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any additional members
on its own. LinkedHashSet internally uses a linked list to store the elements. It is a generic class that has
the declaration:
Searching for an element in stack is called peep operation. Insertion and deletion of elements
take place only from one side of the stack, called top of the stack.
We can write a Stack class as:
class Stack<E>
e.g.: Stack<Integer> obj = new Stack<Integer> (); Stack
Class Methods:
Program : Write a program to perform different operations on a stack.
import java.util.*;
class Stack1
{
int top = -1, st[]=new int[5];
void push(int el)
{
st[++top]=el;
}
int pop()
{
return(st[top--]);
}
void display()
{
System.out.println("\nStack elements from top to bottom\n"); for(int
i=top;i>=0;i--)
System.out.println(st[i]);
}
boolean isFull()
{
return(top==5-1);
}
boolean isEmpty()
{
return(top==-1);
}
}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); Stack1 s
= new Stack1();
int el = 0, ch=1;
while(ch != 4)
{
System.out.println("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT"); System.out.println("ENTER
YOUR CHOICE");
ch=sc.nextInt();
switch(ch)
{
case 1 :
if(s.isFull()) System.out.println("\nstack
is full"); else
{
System.out.println("Enter element");
el=sc.nextInt();
s.push(el);
}
break;
case 2:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else
{
el=s.pop();
System.out.println("\nDeleted element = "+el);
}
break;
case 3:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else
s.display(); break;
case 4:
break;
default:
System.out.println("\nEnter correct choice");
}
}
sc.close();
}
}
OUTPUT:
C:\Users\Anil\Desktop\2018 Java>javac Stack.java
C:\Users\Anil\Desktop\2018 Java>java Stack
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
10
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
20
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
30
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 30
20
10
PUSH
1. POP
2. DISPLAY
4.EXIT
ENTER YOUR CHOICE 1
Enter element
40
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 40
30
20
10
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 50
40
30
20
10
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 2
Deleted element = 50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 4
ArrayList Class
ArrayList Class: An ArrayList is like an array, which can grow in memory dynamically. ArrayList is
not synchronized. This means that when more than one thread acts simultaneously on the ArrayList
object, the results may be incorrect in some cases.
package com.myPack;
import java.util.ArrayList;
import java.util.Iterator;
al.add ("Europe");
al.add (1,"Australia");
al.add (2, "Antarctica");
al.add (4, "Carona");
System.out.print ("Size of the Array List is: \n" +al.size ()); System.out.print
("\nRetrieving elements inArrayList using Iterator :\n"); Iterator<String> it =
al.iterator ();
while (it.hasNext () ) System.out.print
("\n" +it.next ());
}
}
Output:
Size of the Array List is:
8
Retrieving elements in ArrayList using Iterator : Asia
Australia Antarctica
North Ameria CaronaCarona
South AmericaAfrica Europe
Program on ArrayList
LinkedList Class: A linked list contains a group of elements in the form of nodes. Each node will
have three fields- the data field contatins data and the link fields contain references to previous and
next nodes.A linked list is written in the form of:
class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
LinkedList Class methods:
Note: In case of LinkedList counting starts from 0 and we start counting from 1.
ll.add (2,"Abhimanyu");
System.out.println ("Elements in Linked List is :\n "+ ll);System.out.println ("Size of the
Linked List is : \n" + ll.size() );
}
}
Output:
Elements in Linked List is:
[Eega, Abishai, Abhimanyu, Anil, Bharathi, Charan,Chiranjeevi]
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to
store application-specific information. So, interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC (Open database connectivity) driver. This
driver is used with JDBC to interact or communicate with various kinds of databases such as
Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can interact with a database.
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA (write once run anywhere) capabilities. The java.sql package
contains interfaces and classes of JDBC API.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.
3. JDBC Test suite: It is used to test the operation (such as insertion, deletion, updation)
being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of the
sun.jdbc.odbc package which includes a native library to access ODBC characteristics.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4
types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver (partially java driver)
Type-3 driver or Network Protocol driver (fully java driver)
Type-4 driver or Thin driver (fully java driver)
a. JDBC CRUD (Create, Read, Update and Delete) example
Step 1: Establish connection with database
Step 2: Create following table in MySQL database server
use test;
create table Emp(
code varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
Step3 : Following code to insert record in the above table -
public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement(“insert into Emp values(?,?,?,?)”);
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“Inserted”);
} else {
System.out.println(“not Inserted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step4 : Following source code is to update employee city and salary based on employee code -
public void updateEmp(String code, String city, int salary) {
try {
ps = con.prepareStatement(“update emp set city=?,salary=salary+? where code=?”);
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“updated”);
} else {
System.out.println(“not updated”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step5 : Following source code is to delete an employee record based on employee code -
public void deleteEmp(String code) {
try {
ps = con.prepareStatement(“delete from emp where code=?”);
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“deleted”);
} else {
System.out.println(“not deleted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step6 : Following source code is to display an employee record based on employee code -
public void dispAnEmp(String s) {
try {
ps = con.prepareStatement(“select * from Emp where code=?”);
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Step7 : Following source code is to display whole records from employee table -
public void dispAll() {
try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery(“select * from Emp”);
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}