Professional Documents
Culture Documents
Threads AND NERWOKING
Threads AND NERWOKING
Threads AND NERWOKING
Each process has an address in memory. In other words, each process allocates a separate
memory area.
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.
Thread-based Multitasking (Multithreading)
New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other is running.
Explanation of Different Thread States
◦ Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the
thread may be running or may be ready to run at any given instant of time. It is the duty of the thread
scheduler to provide the thread time to run, i.e., moving the thread the running state.
◦ Running: A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time slice is over,
the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for
their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
◦ 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
Explanation of Different Thread States
◦ 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
For example, a thread (let's say its name is A) may want to print some data from the printer. However,
at the same time, the other thread (let's say its name is B) is using the printer to print some data.
Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A
thread in the blocked state is unable to perform any execution and thus never consume any cycle of the
Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler
reactivates thread A, which is in the waiting or blocked state.
Explanation of Different Thread States
◦ 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.
Explanation of Different Thread States
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.
Explanation of Different Thread States
How to create a thread in Java
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
◦ Thread()
◦ Thread(String name)
◦ Thread(Runnable r)
◦ Thread(Runnable r,String name)
Commonly used methods of Thread class:
A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is in
the runnable state. However, if there is more than one thread in the runnable state, it is up to
the thread scheduler to pick one of the threads and ignore the other ones. There are some
criteria that decide which thread will execute first. There are two factors for scheduling a thread
i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means
that thread has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a case, arrival time of
thread is considered by the thread scheduler. A thread that arrived first gets the preference over
the other threads.
Thread Scheduler Algorithms
1. The ticket booking system should have a limited number of available tickets, let's say 50.
2. Multiple threads representing customers will attempt to book tickets concurrently.
3. A customer thread should randomly choose a number of tickets to book, ranging from 1 to 5.
4. If the requested number of tickets is available, the booking should be successful, and the number of available
tickets should be updated.
5. If the requested number of tickets is not available, the customer should be notified that the booking failed.
6. The program should keep track of the total number of tickets booked by all customers.
7. Write a Java program that satisfies the above requirements using threads and synchronization mechanisms.
Java Networking
Java Networking?
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
Advantage of Java Networking
◦ Sharing resources
◦ Centralize software management
Java Networking?
The java.net package supports two protocols,
◦ TCP: Transmission Control Protocol provides reliable communication between the sender and receiver.
TCP is used along with the Internet Protocol referred as TCP/IP.
◦ UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to
be transferred along two or more nodes
Java Networking?
Java Networking Terminology
◦ IP Address
◦ Protocol
◦ Port Number
◦ MAC Address
◦ Connection-oriented and connection-less protocol
◦ Socket
java.net package
The java.net package can be divided into two sections:
◦ A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e.
bidirectional data communication mechanism and Interfaces i.e. network interfaces.
◦ A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e.
Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs.
java.net package
The java.net package provides many classes to deal with networking applications in Java. A list of
these classes is given below:
Authenticator,CacheRequest, CacheResponse, ContentHandler,CookieHandler, CookieManager,
DatagramPacket, DatagramSocket,DatagramSocketImpl,
InterfaceAddress, JarURLConnection, MulticastSocket ,InetSocketAddress,
InetAddress,Inet4Address,Inet6AddressIDN,HttpURLConnection,HttpCookie,NetPermission,Net
workInterface,PasswordAuthentication,Proxy,ProxySelector,ResponseCache,SecureCacheRespon
se,ServerSocket,Socket,SocketAddress,SocketImpl,SocketPermission,StandardSocketOptions,URI
,URL,URLClassLoader,URLConnectionURLDecoder,URLEncoder,URLStreamHandler
Java Socket Programming
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.
The client in socket programming must know two information:
◦ IP Address of Server, and
◦ Port number.
Java Socket Programming
Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are
being used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.
Java 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.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with
this socket.
2) public OutputStream returns the OutputStream attached with
getOutputStream() this socket.
3) public synchronized void close() closes 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.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a
connection between server and
client.
2) public synchronized void closes the server socket.
close()
Example of Java Socket Programming
Creating Server:
◦ To create the server application, we need to create the instance of ServerSocket class. Here, 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.
1. ServerSocket ss=new ServerSocket(6666);
2. Socket s=ss.accept();//establishes connection and waits for the client
Example of Java Socket Programming
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.
Socket s=new Socket("localhost",6666);
Example of Java Socket Programming
1.import java.io.*;
2.import java.net.*;
3.public class MyServer {
4.public static void main(String[] args){
5.try{
6.ServerSocket ss=new ServerSocket(6666);
7.Socket s=ss.accept();//establishes connection
8.DataInputStream dis=new DataInputStream(s.getInputStream());
9.String str=(String)dis.readUTF();
10.System.out.println("message= "+str);
11.ss.close();
12.}catch(Exception e){System.out.println(e);}
13.}
Example of Java Socket Programming
1.import java.io.*;
2.import java.net.*;
3.public class MyClient {
4.public static void main(String[] args) {
5.try{
6.Socket s=new Socket("localhost",6666);
7.DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8.dout.writeUTF("Hello Server");
9.dout.flush();
10.dout.close();
11.s.close();
12.}catch(Exception e){System.out.println(e);}