Java Unit 4
Java Unit 4
UNIT 4
4.1. Multithreading in java
4.1.1. Thread life cycle and methods
4.1.2. Runnable interface
4.1.3. Thread Synchronisation
4.1.4. Exception handling with try-catch-finally
4.1.5. Collections in Java
4.1.6. Introduction to Java and network
programming
2
Thread
It is a light weight of process. Process means the execution of the program.
Multithreading
Two or more number of threads is executed during the same time known as
multithreading.
Types of Threads
1. Daemon thread
2. User thread
1. Daemon thread
They are usually designed to run the background for the purpose of servicing the
user thread.
Example: Garbage collection.
2. User thread
The user creates his own threads in the java program.
The run() method is a core part of threads in java. This method is entry point and
exit point for any thread recreate.
class ThreadDemo
{
public static void main(String args[])
{
}
}
Step 7: t1.start();
class MultipleThreads
{
public static void main(String args[])
{
ThreadA ta=new ThreadA();
ThreadB tb=new ThreadB();
ThreadC tc=new ThreadC();
Thread t1=new Thread(ta,"Thread one");
6
The life cycle of the thread is basically starts from start() method this thread is used to
execute the main thread and complete it. After this picked up the threads execution
from the run() method one by one until the completion of all the threads.
Ready to run state: A thread is ready to run state and it is eligible for execution which
ever thread comes first the start() method is execute that thread. If the thread state is
not ready to run it should be blocked or waiting or it is sleeped.
Not ready to run: If thread is not ready to execute and it is not running, that should be
following another 3 states.
1. Sleeping
2. Waiting
3. Blocked
7
1. Sleeping: Incase thread is not ready that particular thread will be sleeped for the
some period of time that must be declared as Thread.sleep();
2. Waiting: If thread is not ready to execute it must be execute after some time we
should use the method wait().
3. Blocked: If thread is not execute and not running properly or problems in network
resources or not interested to execute the particular thread these times thread will
be blocked. After getting all the resources we will call isAlive() method.
Methods of thread
I. current thread():
It shows the current running thread.
II. getName()
It returns the name of the thread.
class CurrThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t.getName());
}
}
III. setName()
It Set’s the name of the thread.
}
class CurrThread
{
public static void main(String args[])
{
System.out.println(Thread.currentThread().getName());
ThreadA ta = new ThreadA();
ta.setName("Thread one");
Thread t = new Thread(ta);
System.out.println(t.getName());
}
}
IV. Sleep()
It is used to sleep for the specified amount of time in a current thread.
class ThreadSleep
{
public static void main(String args[])
{
Thread t= Thread.currentThread();
System.out.println("Before sleep");
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("I slept for 10 seconds");
}
}
}
V. setPriority()
It Set’s the priority of the thread.
VI. getPriority()
By default the getPriority is 5, if we want to set more than 5 we should use
setPriority.
9
class ThreadPriority
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Main thread Priority :"+t.getPriority());
t.setPriority(10);
System.out.println("Main Thread Priority :"+t.getPriority());
}
}
VII. stop()
It is used to kill the thread.
VIII. start()
It is used to execute the beginning of the thread execution and calls in the run()
method.
IX. wait()
It is used to wait the next Thread execution until the current thread is executed.
X. suspend()
Suspend the thread or it is completely blocked in a thread.
XI. resume()
Pausing the current thread.
SYNCHRONIZATION
When using multiple threads it is sometimes necessary to co-ordinate the activities
of two or more. This process by which this is achieved is called as synchronization.
Example
Assume that a husband and wife use an ATM card that does'nt incorporate
synchronization. The husband goes to ATM system to withdraw Rs: 1000 from the joint
a/c. the wife does the same thing in another part of the town. The account has only 1200
10
rupees in it the husband check the account has at least 1200 in it. The ATM shows that
the money is there while the husband is preparing to withdraw the money. The wife
checks the same a/c on the ATM across town. The ATM shows the A/C has 1200 in it. So
she also decides to withdraw 1000 rupees from the account at the extra same time. They
both select the withdraw option. Since the ATM has not synchronization the two ATM
they both check to see that at least 1200. rupees is in the A/C and since its the perform
withdrawal. The result that the couple has now overdraws their A/C or only one person
has successed. The other one will in confusing state. This type of situation is handled by
the technique of synchronization. Synchronization is a keyword that is used to execute
the multi-threading concept with co-ordination b/w two threads and execute smoothly
otherwise it’s locked or blocked.
General Syntax:
synchronization void withdraw()
{
}
When we want to block the multiple thread we want to use the following.
synchronization(object)
{
}
class Nonsynchronized
{
public static void main(String args[])
{
Parentheses P3 = new Parentheses();
MyThread ta1 = new MyThread(P3, "Srikanth");
Thread t1 = new Thread(ta1);
MyThread ta2 = new MyThread(P3, "Srigdha");
Thread t2 = new Thread(ta2);
t1.start();
t2.start();
}
}
DEFINITION OF SYNCHRONIZATION
class ThreadRunnable
{
public static void main(String args[])
{
System.out.println("Main thread started");
Mythread obj=new Mythread();
Thread t1 = new Thread(obj);
t1.start();
System.out.println("Main thread completed");
}
}
JAVA COLLECTION
The collection of java objects that is used to perform the operation such as searching,
sorting, insertion, manipulation and deletion etc.
The structure of JCF (Java Collection Frame) is used to collect different variety of object
as shown by following figure.
14
1. Interface
Interface is a collection of abstract data type that is used to represent java
collection frame work.
Example: List is an interface in collection frame work.
2. Implementation or classes
The several numbers of interfaces having several numbers of abstract method, then
implementing of this method inside the class only and also implement several
number of classes such as
1. Array list
2. linked list
3. Hash map
4. Tree map
5. Hash set
6. Tree set……etc.
Example: the array list and linked are implementation classes of list interfaces
3. Algorithms
The algorithms are used is perform the different types of methods and its
computation such as searching and sorting objects can implement in java
collection.
15
Example:
add (object o)
remove (object o)
are the methods of array list and linked list
Array is a fixed size of memory allocation do not increase during at rum time and if we
take less member of items the remaining memory is wastage the array of objects is the
best concept for taking the number of recodes stored in a memory allocation.
object[] obj = new object[10];
obj [0] = new customer();
obj [1] = new customer():
obj [2] = new string(“Manoj”);
Arrays is a fixed size of memory allocation do not increase during at rum time and if we
take less number of items the remaining memory is wastage.
The arrays of objects are the best concept for taking the number of records sorted in a
memory allocation.
object[] obj = new object[10];
obj [0] = new customer();
obj [1] = new customer():
obj [2] = new string(“Manoj”);
Here this object is used to take several items with several number of categories so that
we need the collection frame work in java
16
arrays collection
Arrays is a fixed size Collection is used to increase or
decrease the size
Arrays can hold both primitive as well Collection can hold only object but not
as object primitive
The performance of an arrays is faster The performance of a collection is
than collection slower than arrays.
Arrays can hold only homogeneous Collection can hold both homogeneous
and heterogeneous
The memory allocation of arrays are The memory allocation of an collection
not recommended to use are recommended to collection
Readymade methods are not available Readymade methods are available in
in array collection
Iterator interface
iterator()
It returns an iterator of type E for the collection. It can be used to iterator over the
elements of the collection.
Collection Interface
• The collection Interface is the foundation on which the collection framework is built.
• Collection interface provides all general purpose methods which all collections
classes must supports.
• Collection interface extends iterable interface which adds support for iterating
over collection elements using the “for-each loop” statement.
Methods Description
add(object o) To insert an element in the collection
addAll(collection c) To insert another collection in the present collection
remove(object o) To remove an element in the collection
removeAll(collection c) To remove another collection from the present
collection of another is inserted
18
List Interface
It is used for searching. If element of another collection are present in the collection or
note. If present returns true or false. The subclasses implement the list interface, so the
list object can be instantiated using subclasses. Below is the syntax to instantiate the
subclasses mentioned here:
Methods Description
add() Adds an elements to a list
addAll() Adds all elements of one list to another
get() Help to randomly access elements from list
iterator() Returns iterator object that can be used to Sequentially access
elements of lists.
set() Changes elements of list
remove() Remove an elements from the list
removeAll() Removes all the elements from the list
clear() Removes all the elements from the list(more efficient than
removeAll())
size() Returns the length of list
toArray() Converts a list into an array
contains() Returns true if a list contains specified element
Set Interface
Set is child interface of collection. It doesn’t have methods. All methods are
inherited from collection.
Below is the syntax to instantiate the classes that implement the set interface:
Set <datatype> obj1=new HashSet <data type>();
Set <datatype> obj2=new LinkedList <data type>();
Set <datatype> obj3=new TreeSet <data type>();
Here, Data type refers to the data type of the instances obj1, obj2, obj3.
Queue Interface
Queue is the child interface of collection. The queue interface of the java
collections framework provides the functionally of the queue data structure.
Below is the syntax to instantiate the classes that implements the queue interface:
Queue<datatype> q1= new priorityQueue<>();
Queue<datatype> q2= new ArrayDequeue<>();
20
Methods Description
add() Inserts the specified element into the queue .If the task is successful,
add() returns true, if not it throws an exception.
offer() Insert the specified elements into the queue. It the task is successful,
offer() returns true, if not it returns false.
elements() Returns the head of the queue. Throws an exception if the queue is
empty.
peek() Returns the head pf the queue. Return null if the queue is empty.
remove() Returns and remove the head of the queue. Throws an exception if the
queue is empty.
poll() Returns and removes the head of the queue. Returns null if the queue is
empty.
Deque Interface
• Deque is the child interface of the queue.
• Deque also known as a double-ended queue.
• Deque allow us to add and remove the elements from both the ends of the queue
• Deque interface implemented by class ArrayDeque.
• We can instantiate the Deque object with any of its implemented classes as follow:
Map Interface
All the above interfaces (collection, list, set, sortedset, NavigableSet and Queue) can
be used to represent group of individual objects.
If we want represent a group of object as key value pairs then we should go for Map
interface.
We can instantiate the map object with any of its implemented classes as follows.
Methods Description
put(k,v) Insert the association of a key k and a value v into
the map. If the key is already present, the new
valuereplaces the old value.
replace(k,oldvalue,newValue) Replaces the value of the key k with the new value
newValue only if the key k is associated with the
value oldValue.
remove(k,V) Removes the entry from the map that has key K
associated with value V.
ArrayList
In java, we use the ArrayList class to implement the functionality of resizable-arrays. It
implements the list interface of the collections framework.
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first.
Here is how we can create arraylists in java:
ArrayList<type> arrayList =new ArrayList<>();
Here, <type> indicates the type of an arraylist.
For Example:
Example:
ArrayList<String> langList=new ArrayList<>();
langList.add("Java");
langList.add("c");
langList.add("Python");
In the above example, we have created an ArrayList named langList. Here, we have
used the add() method to add elements to langList.
Example:
String str=langList.get(0);
//Getting the other element and storing it in str
System.out.println("Element at index 0:"+str);
//prints java
System.out.println("Element at index 1:" +langList.get(1));
//prints C
System.out.println("Elements at index 2:" +langList.get(2));
// prints Python
24
In the above code, we have used the get() method with parameter 0. Here, the method
returns the elements of the ArrayList using the iterator() method. We will discuss
about iterator later.
Example:
ArrayList<String> langlist=new ArrayList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
// change the element of the array list language.set(2,"JavaScript");
Example:
ArrayList<String> langList=new ArrayList<>();
langList.add("java");
langList.add("C");
langList.add("Python");
//remove element from index 2 String str=langList.remove(2);
Here, the remove() method takes the index number as the parameter. And, removes
the element specified by the index number.
We can also remove all the elements from the arraylist at once by using removeAll()
and clear() methods of ArrayList class.
Methods Description
size() Returns the length of the arraylist.
sort() Sort the arraylist the elements.
clone() Create a new arraylist with the same element, size, and capacity.
contain() Searches the arraylist for the specified element and returns a
boolean result.
ensurecapacity() Specifies the total element the arraylist can contain.
isempty() Checks if the arraylist is empty
indexof() Searches a specified element in an arraylist and returns the index
of the element.
// ArrayList Demo
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> langList=new ArrayList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
System.out.println("ArrayList :"+langList);
System.out.println("Accessing indidvidual element:");
for(String language : langList)
{
System.out.println(language);
}
}
}
LinkedList
The linkedList class of the java collections framework provides the functionality
of the linked list data structure (doubly linkedlist).
26
import java.util.LinkedList;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> animals=new LinkedList<>();
animals.add("dog");
animals.add("Cat");
animals.add("Cow");
27
System.out.println("LinkedList :"+animals);
animals.add(1,"Horse");
System.out.println("Update LinkedList:"+animals);
}
}
Example:
LinkedList<String> langList=new LinkedList<>();
langList.add("Python");
langList.add("Java");
langList.add("c");
String str=langList.get(0);
System.out.println("Element at index 0:"+str);
System.out.println("Element at index 1:"+langList.get(1));
System.out.println("Element at index 2:"+langList.get(2));
Example:
LinkedList<String> langList = new LinkedList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
langList.set(2,"JavaScript");
Example:
LinkedList<String> langList=new LinkedList<>();
langList.add("java");
28
langList.add("C");
langList.add("Javascript"); String str=langList.remove(1);
System.out.println("Removed Element :"+str);
langList.removeAll();
LinkedList ArrayList
1. Implements List and Deque interfaces. 1. Implements List interface.
LinkedList class can act as a list and An ArrayList class can act as a list only
queue both because it implements List because it implements List interface
and Deque interfaces. only.
29
What is JavaBean?
JavaBeans are basically POJOS (Plain Old Java Object), defined according to the
norms based on the software component model. JavaBeans is a portable, platform-
independent model written in Java Programming Language. Its components are
referred to as beans.
In simple terms, JavaBeans are classes which encapsulate several objects into a single
object. It helps in accessing these object from multiple places. JavaBeans contains several
elements like Constructors, Getter/Setter Methods and much more.
JavaBean Conventions
JavaBeans has several conventions that should be followed:
• Beans should have a default constructor(no arguments)
• It should provide methods to set and get the values of the properties, known as getter
and setter methods.
• A getter method is used to read the value of a readable property
• To update the value a setter method should be called.
• It should be Serializable Beans should implement java.io.serializable, as it
allows to save, store und restore the state of a JavaBean.
JavaBean Properties
1. getPropertyName()
This is called getter method.
For example, if the employee name is empName, the method name would be
getEmpName() to read that employee name. This method is known as an accessor.
2. setPropertyName()
This method is known as a mutator.
For example if the employee name is empName, the method name would be
setEmpName() to write that employee name.
{
return age;
}
public void setAge (int age)
{
this.age =age;
}
}
Advantages of JavaBean
A Bean obtains all of the benefits of Java's "write once run anywhere" paradigm.
The JavaBean properties and methods can be exposed to another application.
The configuration settings of a Bean can be saved in a persistent storage and can be
restored at a later time.
It provides an easiness to reuse the software components. A Bean may register to
receive events from other objects and can generate events that are sent to it.
Disadvantages of JavaBean
• JavaBeans are mutable. So, it can't take advantages of immutable objects.
• Having to create a getter for every property and a setter for many, most or all of
them, creates an immense amount of boilerplate code.
33
2. UDP - UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
A client may send more than one request through an open connection. In fact, a client
can send as much data as the server is ready to receive. The server can also close the
connection if it wants to.
Java Networking Terminology
The widely used java networking terminologies are given below:
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket
Socket Programming
• Socket Programming refers to communication between two nodes or applications
running on different JRE (Java Runtime Environment). We use the socket
programming in Java to connect the client program with the server program, or
simply, connect a client and a server.
• Socket programming in Java can be either connection- oriented or connectionless.
The package java.net is used for socket programming in Java. There are two classes
in this package which are Socket class and ServerSocket class.
• When a client wants to open a TCP/IP connection to a server, it does so using a Java
Socket. The socket is told what IP address and TCP port to connect to and the rest is
done by java.
• The java Socket Programming has two sections.
(a) Java Server Socket Program
(b) Java Client Socket Program.
35
Methods Description
public void connect(SocketAddress This method connects the socket to
host, int timeout) throws the given input host.
IOException
public int getPort() This method returns the port through
which the socket is bound on the
remote machine.
public int getLocalPort() This method returns the port through
which the socket is bound on the local
machine.
public SocketAddress This method gives the address of the
getRemoteSocketAddress() remote socket.
public InputStream getInputStream() This method returns the input stream
throws IOException of the socket
Public void close() throws This method closes the socket. Closing
IOException the socket makes it no longer
available to connect it to any server.
Methods Description
public int getLocalPort() This method returns the port on which
the server socket is listening to.
public Socket accept() throws It returns the socket and establishes a
IOException connection between the server and the
client.
public void setSoTimeout(int This method sets the time- out value for
timeout) how long the server socket has to wait for
a client during the accept() method.
public void bind (SocketAddress This method binds the socket to the
host, int backlog) specified server and port in the
SocketAddress object.
public synchronized void close() This method closes the object of the
ServerSocket class.
36
2. Writing to a Socket
To write to a Java Socket we must obtain its OutputStream. Here is how that is done:
Socket clientSocket = new Socket("127.0.0.1", 5000);
OutputStream out= socket.getOutputStream();
Printwriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
out.println("Hello Server");
clientSocket.close();