NP Lab Theory:: 1) To Create Thread by Inheriting Thread Class
NP Lab Theory:: 1) To Create Thread by Inheriting Thread Class
MULTI-THREADING:
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
thread and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.Threads reduce inefficiency by preventing the waste of CPU
cycles.
Threads exist in several states. Following are those states:
● New – When we create an instance of Thread class, a thread is in a new state.
● Runnable – The Java thread is in running state.
● Suspended – A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it left
off.
● Blocked – A java thread can be blocked when waiting for a resource.
● Terminated – A thread can be terminated, which halts its execution immediately at
any given time. Once a thread is terminated, it cannot be resumed.
CREATING THREADS:
Java’s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. To create a new thread, your program will either extend Thread or
implement the Runnable interface.
The second way to create a thread is to create a new class that extends Thread, then
override the run() method and then to create an instance of that class. The run()
method is what is executed by the thread after you call start().
2) To create Thread by implementing Runnable interface:
RUNNABLE INTERFACE:
The easiest way to create a thread is to create a class that implements the Runnable
,isAlive ,sleep:
The setPriority() method of thread class is used to change the thread's priority. Every thread has a
priority which is represented by the integer number between 1 to 10.
public static int MIN_PRIORITY: It is the maximum priority of a thread. The value of it is 1.
public static int NORM_PRIORITY: It is the normal priority of a thread. The value of it is 5.
public static int MAX_PRIORITY: It is the minimum priority of a thread. The value of it is 10.
We can also set the priority of thread between 1 to 10. This priority is known as custom priority or
user defined priority.
Syntax
Parameter
Return
Exception
IllegalArgumentException: This exception throws if the priority is not in the range MIN_PRIORITY to
MAX_PRIORITY.
SecurityException: This exception throws if the current thread cannot modify this thread.
The getPriority() method of thread class is used to check the priority of the thread. When we create
a thread, it has some priority assigned to it. Priority of thread can either be assigned by the JVM or
by the programmer explicitly while creating the thread.
The thread's priority is in the range of 1 to 10. The default priority of a thread is 5.
Syntax
Return
The getName() method of Method class returns the name of the method represented by this
Method object, as a String.
Syntax
Parameter
No parameter is passed.
Returns
Throws
The setName() method of thread class is used to change the name of the thread.
Syntax
Parameter
Return
Exception
SecurityException: This exception throws if the current thread cannot modify the thread.
Syntax
Return
This method will return true if the thread is alive otherwise returns false.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
4)To copy the content of one file to another using byte oriented i/o:
The Java Input/output (I/O) is a part of java.io package. The java.io package contains a relatively
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream. There are many byte stream classes. To
demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and
FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in
5)To copy the contents of one file to another using character oriented i/o:
FileReader: We can use this class to read a character data from the file.
Constructors:
Methods:
int read(): It attempts to read next character from the file and returns its Unicode value. If the next
value is not available then this method returns ‘-1’. As this returns Unicode value, at the time of
printing we have to perform typecasting.
int read(char[] ch):It attempts to read enough characters from the file into character array and
returns number of characters copied from the file. Object.
PrintWriter: It is the most enhanced writer to write charcter data to the file. The main advantage
of printWriter over BufferedWriter and FileWriter is we can write any type of primitive data directly
to the file. PrintWriter can communicate directly with the file and can communicate via writer object
also.
Constructors:
Methods:
character stream classes that specialize in file I/O: FileReader and FileWriter. Character Streams that
Use Byte Streams Character streams are often "wrappers" for byte streams. The character stream
uses the byte stream to perform the physical I/O, while the character stream handles translation
between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses
InputStreamReader and OutputStreamWriter. Use them to create character streams when there are
6) To copy the contents of one file to another using line oriented i/o:
BufferedReader: We can use BufferedReader class to read character data from the file .The
main advantage of BufferedReader when compared to FileReader is we can read the data line by
line in addition to character by character. BufferedReader cannot communicate directly with the
file and it can communicate via some Reader object.
Constructors:
Methods:
String readLine(): It attempts to read next line from the file and returns it. If the next line not
available then this method returns null.
PrintWriter: It is the most enhanced writer to write charcter data to the file. The main advantage
of printWriter over BufferedWriter and FileWriter is we can write any type of primitive data directly
to the file. PrintWriter can communicate directly with the file and can communicate via writer object
also.
Constructors:
Methods:
void Println(int a): This method prints the integer and then terminates the line.
void Println(char ch): It is used to prints the character and then terminates the line.
void println(char[] x):This method prints an array of characters and then terminates the line.
void Println(String s This method prints the string and then terminates the line
Line-Oriented I/O
Character I/O usually occurs in bigger units than single characters. One common unit is the line: a
string of characters with a line terminator at the end. A line terminator can be a carriagereturn/line-
feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n"). Supporting all
possible line terminators allows programs to read text files created on any of the widely used
operating systems.
7) To read a string, int, float and double from keyboard using scanner
class:
This class accepts a File, InputStream, Path and, String objects, reads all the primitive data
types and Strings (from the given source) token by token using regular expressions. By
default, whitespace is considered as the delimiter (to break the data into tokens).
To read data from keyboard you need to use standard input as source (System.in). For each
datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(),
nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(),
nextFloat(), next().
8)to identify the active ports on local system
Active ports:
A port is an integer value ranging from 1 to 65535. It is used to uniquely identify an
application in a system, i.e. no two applications can run at the same port. Port numbers from
1 to 1023 are reserved for well-known protocols like HTTP, SMTP, FTP, TELNET, POP etc.
Ports used by some well-known protocols are given table 1.1. Ideally the port number is user
configurable. Alternatively, if a port number of 0 is specified, the operating system will select
an arbitrary valid and free port every time that the application is run. There are 65535 ports
per transport layer protocol i.e. we can have a UDP application and a TCP application
running at the same port. But two TCP applications or two UDP applications cannot run at
the same port.
Application Protocol port Transport protocol purpose
Echo 7 Tcp/udp Echo is a test protocol
used to verify that two
machines are able to
connect by having one
echo back the other’s
input
FTP 21 Tcp This port is used to
send ftp commands
like put and get
Telnet 23 Tcp Telnet is a protocol
used for intertractive
remote command line
sessions
SMTP 25 Tcp The simple mail
transfer protocol is
used to send a mail
HTTP 80 Tcp Hypertext transfer
protocol is the
underlying protocol of
the world wide web
POP 110 Tcp Post office protocol is
a protocol for the
transfer of
accumulated email
from the host to
sporadically connected
clients
NNTP 119 Tcp Usenet news transfer
is more formally
known as the network
news transfer
protocolnn
16) SMTP Client: Gives the server name, send an email to the recipient
using SMTP Commands
Simple Mail Transport Protocol (SMTP) is the protocol (mechanism) used to get email from
the sending computer all the way to the recipient's email server (SMTP server). This could be
at a company, an ISP, or a web mail hosting service (like Hotmail, Gmail, etc.). SMTP
servers run at port 25.
The sent message is stored on the SMTP server until it is retrieved. The message is then
removed from the server and stored on the local hard drive by POP3. So, it is important to
note 55 (that all successfully retrieved mail needs to be backed up at the local level, if
deemed necessary).
17) POP Client: Gives the server name, username and password, retrieve
the mails and allow manipulation of mailbox using POP commands.
Post Office Protocol Version 3(POP3) is the protocol used to download the email message
from a mail server to a computer using an email client program (like Outlook). When you
check your email, the messages are transferred to your computer and deleted from the server.
Web mail doesn't use POP3, because the messages stay on the server. You are viewing them
remotely. POP server runs at port 110.
The sent message is stored on the SMTP server until it is retrieved. The message is then
removed from the server and stored on the local hard drive by POP3. So, it is important to
note 55 (that all successfully retrieved mail needs to be backed up at the local level, if
deemed necessary).
18) Develop a program to implement UDP Echo Server and UDP Echo
Client.
UDP:
Java’s implementation of UDP is split into two classes: datagram packet and datagram
socket. The datagram packet class stuff byte of data into UDP packets called datagram and
let you unstuffed data grams that we receive. A datagram socket sends as well as receives
UDP datagrams.UDP does not have any notation of server socket. We use the same kind of
socket to send data and receive data.
DatagramPacket Class
Public final class DatagramPacket extends object
Constructors for receiving datagram
1. Public DatagramPacket(byte[] buffer, int length)
When a socket receives a datagram, it stores the datagram’s data part in buffer beginning at
buffer[0] and containing until the packet is completely stored or until ‘length’ bytes have
been written into the buffer.
Public DatagramPacket(byte[] buffer, int offset, int length)
This stores the data beginning at byte[offset] ‘length’ must be lessthan or equal to
buffer.Length-offset or else IllegalArgumentException will be thrown.
Constructors for sending datagram
public DatagramPacket(byte[] data, int length, InetAddress destination, int port)
public DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)
Each constructor creates a new datagram packet to be sent to another host.
Get Methods
public InetAddress getAddress()
It returns an InetAddress object containing the address of the remote host.
Public int getPort()
It returns an integer specifying the remote port.
Public byte[] getData()
It returns a byte array containing the data from the datagram.
Public int getLength()
It returns the number of bytes of data in the datagram it may not be same as the length of
the
array returned by the getData()
Public int getOffset()
It returns the point in the array returned by getData() where the datagram begins.
Set Methods
public void setData(byte[] data)
public void setData(byte[] data, int offset, int length)
public void setAddress(InetAddress remote)
public void setPort(int port)
public void setLength(int length)
DatagramSocket class
All datagram sockets are bound to a local port, on which they listen for incoming data and
which they place in the header of outgoing datagram.
Constructors
Public DatagramSocket() throws SocketException
It creates a socket bound to an anonymous port.
Public DatagramSocket(int port) throws SocketException
It creates a socket that listens for incoming datagram’s on a specified port.
Public DatagramSocket(int port, InetAddress address) throws SocketException
This constructor is used on multi homed hosts.
Public void send(DatagramPacket dp) throws IOException)
This method is used to send datagram packet using datagram socket.
Public void receive(DatagramPacket dp) throws IOException)
It receives a single UDP datagram from a network and stores it in the preexisting datagram
packet object dp.
Public void close()
It frees the port occupied this socket.
Public int getLocalPort()
It returns the local port on which the socket is listening.
Ip multicasting:
A multicast address is the address of a group of hosts called a multicast group. Multicast
addresses are IP addresses in the range 224.0.0.0 to 239.255.255.255(Class D addresses).
Any data sent to the multicast address is relayed to all the members of the group.
MulticastSocket Class:
public class MulticastSocket extends DatagramSocket
Constructors:
1.public MulticastSocket() throws SocketException
It creates a socket that is bound to an anonymous port (an unused port). It throws a
SocketException if the socket cannot be created.