Unit4-BCA IADC
Unit4-BCA IADC
Faculty of BCA
1.Thread in java
● In operating system you can work and execute with more than one programs
simultaneously. This process is known as multi threading.
Process:
● A process is a self contained execution environment and it can be seen as a program or
application. However a program itself contains multiple processes inside it. Java runtime
environment runs as a single process which contains different classes and programs as
processes.
What is thread?
A thread is a:
● Facility to allow multiple activities within a single process
● Referred as lightweight process
● A thread is a series of executed statements
● Each thread has its own program counter, stack and local variables
● A thread is a nested sequence of method calls
● Its shares memory, files and per-process state
Whats the need of a thread or why we use Threads?
● To perform asynchronous or background processing
● Increases the responsiveness of GUI applications
● Take advantage of multiprocessor systems
● Simplify program logic when there are multiple independent entities
What happens when a thread is invoked?
● When a thread is invoked, there will be two paths of execution. One path will execute the
thread and the other path will follow the statement after the thread invocation. There will
be a separate stack and memory space for each thread.
Thread:
● A thread is actually a lightweight process. Unlike many other computer languages, Java
provides built-in support for multithreaded programming.
● 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 the
execution.
● A multi-threaded program contains two or more parts that can run concurrently and each
part can handle a different task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs.
● Multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
● Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Multitasking
Creation of threads:
● Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
● Threads are implemented in the form of objects that contain a method call run().
● It makes up the entire body of a thread and is the only method in which thread’s
behaviour can be implemented.
Syntax:
public void run()
{
………
}
run() should be invoked by an object of thread and it can be achieved by creating and initiating it
with the help of start().
}
public class ThreadEx {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo("one");
R1.start();
RunnableDemo R2 = new RunnableDemo( "two");
R2.start();
}
}
Lifecycle of thread:
Example:
class A extends Thread
{
public void run()
{
try{
for(int i=0;i<4;i++)
{
if(i==1)
{
yield();
System.out.println("yield method is called");
System.out.println("From thread A:"+i);
}
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
try{
for(int i=1;i<4;i++)
{
System.out.println("From thread B:"+i);
if(i==2)
stop();
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
try{
for(int i=0;i<4;i++)
{
System.out.println("From thread c:"+i);
if(i==1)
{
try
{
sleep(7000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e){
System.out.println(e);
Prepared By:Prof.Shweta JoshiPage 10
Indian Academy Degree College
Faculty of BCA
}
System.out.println("Exit from thread c");
}
}
class ThreadLifecycle
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
System.out.println("Start thread A:");
a.start();
Thread t=Thread.currentThread();
System.out.println("Current thread is:"+t);
System.out.println("Start thread B:");
b.start();
System.out.println("Start thread C:");
c.start();
}
}
6. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
7. public int getPriority(): returns the priority of the thread.
8. public int setPriority(int priority): changes the priority of the thread.
9. public String getName(): returns the name of the thread.
10. public void setName(String name): changes the name of the thread.
11. public Thread currentThread(): returns the reference of currently executing thread.
12. public int getId(): returns the id of the thread.
13. public Thread.State getState(): returns the state of the thread.
14. public boolean isAlive(): tests if the thread is alive.
15. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
16. public void suspend(): is used to suspend the thread(depricated).
17. public void resume(): is used to resume the suspended thread(depricated).
18. public void stop(): is used to stop the thread(depricated).
19. public boolean isDaemon(): tests if the thread is a daemon thread.
20. public void setDaemon(boolean b): marks the thread as daemon or user thread.
21. public void interrupt(): interrupts the thread.
22. public boolean isInterrupted(): tests if the thread has been interrupted.
23. public static boolean interrupted(): tests if the current thread has been interrupted.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
For example:
Without synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
Prepared By:Prof.Shweta JoshiPage 13
Indian Academy Degree College
Faculty of BCA
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
200
10
300
15
400
20
500
25
With synchronization
Using 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.
Example:
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
Prepared By:Prof.Shweta JoshiPage 14
Indian Academy Degree College
Faculty of BCA
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
Prepared By:Prof.Shweta JoshiPage 15
Indian Academy Degree College
Faculty of BCA
100
200
300
400
500
Example:
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Here using synchronized method or block we can acquire lock between t1 and t2 or t3 and t4 but
there is no locking process between t1 and t3 or t2 and t4 so to apply lock static synchronization
is used.
Example:
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
These classes are defined in the Collections framework and implement the List interface.
Example:
/ ArrayList implementation of List
List<String> list1 = new ArrayList<>();
// LinkedList implementation of List
List<String> list2 = new LinkedList<>();
Methods of List
Some of the commonly used methods of the Collection interface that's also available in the List
interface are:
● add() - adds an element to a list
● addAll() - adds all elements of one list to another
● get() - helps to randomly access elements from lists
● iterator() - returns iterator object that can be used to sequentially access elements of lists
● set() - changes elements of lists
● remove() - removes an element 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 lists
● toArray() - converts a list into an array
● contains() - returns true if a list contains specified element
Example:
import java.util.List;
import java.util.ArrayList;
class ListDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Prepared By:Prof.Shweta JoshiPage 21
Indian Academy Degree College
Faculty of BCA
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
Output:
List: [1, 2, 3]
Accessed Element: 3
Removed Element: 2
Collection class:
● Java collection class is used exclusively with static methods that operate on or return
collections. It inherits Object class.
ArrayList class:
● The java.util.ArrayList class provides resizable-array and implements the List interface.
● It implements all optional list operations and it also permits all elements, includes null.
● It provides methods to manipulate the size of the array that is used internally to store the
list.
● The constant factor is low compared to that for the LinkedList implementation.
Constructor list:
Sr.No. Constructor & Description
ArrayList( )
1
This constructor builds an empty array list.
ArrayList(Collection c)
2 This constructor builds an array list that is initialized with the elements of the collection
c.
ArrayList(int capacity)
This constructor builds an array list that has the specified initial capacity. The capacity is
3
the size of the underlying array that is used to store the elements. The capacity grows
automatically as elements are added to an array list.
List of Methods:
Sr.No. Method & Description
1 void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >
size()).
boolean add(Object o)
2
Appends the specified element to the end of this list.
Object get(int index)
Returns the element at the specified position in this list. Throws
9
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >=
size()).
int indexOf(Object o)
10 Returns the index in this list of the first occurrence of the specified element, or -1 if the
List does not contain this element.
Object remove(int index)
12 Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).
Example:
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Prepared By:Prof.Shweta JoshiPage 23
Indian Academy Degree College
Faculty of BCA
Example:
import java.util.*;
public class IterateListExample3
{
public static void main(String args[])
{
List<String> city = Arrays.asList("Boston", "San Diego", "Las Vegas", "Houston", "Miami", "A
ustin");
Iterator<String> cityIterator = city.iterator();
while(cityIterator.hasNext())
{
System.out.println(cityIterator.next());
}
}
}
Output:
Boston
San Diego
Las Vegas
Houston
Miami
Austin
4.Java Bean:
● A java bean is a specially constructed java class written in java and coded
according to the JavaBeans API specifications.
● A java bean is a reusable software component that can be manipulated
visually in an application builder tool.
● Characteristics of JavaBean: Should be serializable and implement the serializable
interface. Provides default,no argument constructor. It may have a number of properties
Prepared By:Prof.Shweta JoshiPage 24
Indian Academy Degree College
Faculty of BCA
which can be read or written. It may have number of “getter” and “setter” method for
properties.
● A bean encapsulates many objects into one object so we can access this object from
multiple places. Java Beans are not actually required to inherit a particular base
class or implement a particular interface.
● Java Bean provides support for introspection (it is a process by which an application
builder discovers the properties, methods and events that are associated with
JavaBeans.), properties, customization, events, persistent storage.
2. Methods: Methods a java bean exports are just normal java methods which can be
called from other components or from a scripting environment.By default all of
a bean’s public methods will be exported but a bean can choose to export
only a subset of its public methods.
3. Events: Events provide a way for one component to notify other components that
something interesting has happened. When the event source detects that
something interesting happens it will call an appropriate method on the event
listener object.
1)getPropertyName()(Read only): This method is called accessor. Return type of this method
must be data type of attribute,because it will return
value of attribute. No parameterized method. Ex.property name is firstName so method would
be getFirstName().
2)setPropertyName()(Write only): This method is called mutator. Return type of this method
must be void because it is used to set value of the
property. Single parameterized method having type of attribute. Ex.property name is firstName
so method name would be setFirstName().
Example:
public class person {
private String firstName = null;
private String lastName = null;
private int age = 0;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Terminology:
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
○ TCP
○ FTP
○ Telnet
○ SMTP
○ POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
or example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
6) Socket
A socket is an endpoint between two way communications.
● Java Socket programming is used for communication between the applications running
on different JRE.
● Java Socket programming can be connection-oriented or connection-less.
● Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Socket class:
● A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.
methods:
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
ServerSocket class:
● The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
methods:
Method Description
1) public Socket accept() returns the socket and establish a connection between server
and client.
Creating Server:
● To create the server application, we need to create the instance of ServerSocket class.
● we are using 6666 port number for the communication between the client and server. You
may also choose any other port number.
● The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
Creating Client:
● To create the client application, we need to create the instance of Socket class. Here, we
need to pass the IP address or hostname of the Server and a port number. Here, we are
using "localhost" because our server is running on same system.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Output: