You are on page 1of 31

• Introduction to Multithreading :

Multithreading is a technique that allows a program or a process to execute many tasks


concurrently . It allows a process to run its tasks in parallel mode on a single processor
system

In the multithreading concept, several multiple lightweight processes are run in a single
process/task or program by a single processor. For Example, when you use a word
processor you perform a many different tasks such as printing, spell checking and so
on. Multithreaded software treats each process as a separate program.

In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of
execution running concurrently. It allows a program to be more responsible to the user.
When a program contains multiple threads then the CPU can switch between the two
threads to execute them at the same time.

For example, look at the diagram shown as:

In this diagram, two threads are being executed having more than one task. The task of
each thread is switched to the task of another thread.

Advantages of multithreading:

• Reduces the computation time.


• Improves performance of an application.
• Threads share the same address space so it saves the memory.
• Context switching between threads is usually less expensive than between
processes.
• Cost of communication between threads is relatively low.
Practical-

Write a program to implement producer-consumer concept using thread.

• Introduction to producer-consumer concept:

The producer-consumer concept is also known as bounded buffer concept. Two


processes share a common fixed size buffer. One of them, producer puts information
into the buffer and the other one consumer consumes information from the buffer.

When consumer wants to remove an item and the buffer is empty, it goes to sleep
until producer puts something in the buffer and wakes it up. Sameway when
producer wants to put new item into the buffer but the buffer is full then producer
goes to sleep to be awakened when consumer has removed one or more item.

In our program producer and consumer are two threads. Synchronization is used to
ensure co-operation between thread.

Critical region: it is a code that only one thread can execute at a time.

Mutual exclusion: Ensures only one thread does a particular activity at a time, all
other threads are excluded doing that activity.

Flow of execution of program:

1) Main () creates the producer and consumer thread.

2) Producer runs and executes run() method from which it accesses the
synchronized method put(). If there is no space in the buffer producer executes
wait() function otherwise producer puts item into the buffer and executes notify()
to wake the consumer up it is in sleep mode.

3) Consumer runs and executes run() method from which it accesses the
synchronized method gut(). If there is no item in the buffer consumer executes
wait() function otherwise consumer consumes item from the buffer and executes
notify() to wake the producer up if it is in sleep mode.

Following code shows producer-consumer implementation using multithreading in


java:

//PC.java

import java.io.*;

class Q

int n; boolean set=false;

synchronized int get()


{

while(set==false)

try

wait();

catch(InterruptedException e)

System.out.println("interrupted exception caught");

System.out.println("got:" +n);

set=false;

notify();

return n;

synchronized void put(int n)

while(set==true)

try

wait();

catch(InterruptedException e)

System.out.println("interrupted exception caught");

}
System.out.println("put:" +n);

this.n=n;

set=true;

notify();

class producer implements Runnable

Q q;

int num;

producer(Q q)

this.q=q;

new Thread(this,"producer").start();

public void run()

int i=0;

while(true)

q.put(i++);

try {

T Thread.sleep(1000);

catch(InterruptedException e)

}
}

class consumer implements Runnable

Q q;

consumer(Q q)

this.q=q;

new Thread(this,"consumer").start();

public void run()

while(true)

q.get();

try {

Thread.sleep(1000);

catch(InterruptedException e)

class PC

{
public static void main(String args[])

System.out.println("press ctrl-c to stop");

Q q=new Q();

new producer(q);

new consumer(q);

• Output of the above code:

Program Files\Java\jdk1.6.0\bin>java PC

press ctrl-c to stop

put:0

got:0

put:1

got:1

put:2

got:2

put:3

got:3

C:\Program Files\Java\jdk1.6.0\bin>

Program-

Write a program to find length of the string using thread.

Flow of execution of the program:

1) Main () takes three strings as input from the user and creates three threads of
execution.

2) Each thread calls run() method individually.

3) From run() thread calls len() method which is declared as synchronized to provide
concurrent access to threads and returns the length of the string.

4) Once length is counted threads are terminated by main() calling join().

Java code is as follows:


//stringlen.java

import java.io.*;

import java.util.Scanner;

class called

synchronized int len(String m)

try

Thread.sleep(1000);

catch(Exception e)

System.out.println("Interrupt");

return m.length();

class caller implements Runnable

String s;

called a;

Thread t;

public caller(called tar,String str)

a=tar;

s=str;

t=new Thread(this);

t.start();

public void run()


{

String thrdnm;

int i=a.len(s);

thrdnm=t.getName();

System.out.println("thread name:" + thrdnm + " -- "+ "length=" + i);

public class stringlen

public static void main(String args[]) throws IOException

String str1,str2,str3;

called c=new called();

System.out.println("enter 3 strings");

Scanner s=new Scanner(System.in);

str1=s.nextLine();

str2=s.nextLine();

str3=s.nextLine();

caller ob1=new caller(c,str1);

caller ob2=new caller(c,str2);

caller ob3=new caller(c,str3);

try

ob1.t.join();

ob2.t.join();

ob3.t.join();

catch(InterruptedException e)

System.out.println("Interrupted");

}
}

• output:

enter 3 strings

welcome

to

ldenggcollege

thread name:Thread-0 -- length=7

thread name:Thread-2 -- length=13

thread name:Thread-1 -- length=2

C:\Program Files\Java\jdk1.6.0\bin>
• Introduction to java RMI:

It is a method invocation to call object methods located remotely sharing resources


and processing load across systems.

RMI allows object to communicate between different java virtual machines. It means
one JVM can invoke methods belonging to object stored in other JVM.

Architecture of RMI:

1) Stub: the stub is a client side object and it represents remote objects.

Tasks performed by stub include:

Initiate connection with remote VM.

Marshal the parameters to remote VM.

Wait for the result.

unmarshal the result value.

Return the value to caller.

2) Skeleton: the skeleton object takes care of the details of remoteness.

Tasks performed by skeleton includes

unmarshal the parameter for the remote method

Invoke the method

Marshal the result to the caller

3) RMI naming service: it is a remote object that is a directory service for clients, key
keeping a hash table like mapping of name to remote object.

*** Procedure to create an RMI application:

Developing an application using RMI includes following steps

1) Define a remote interface:

It includes creating a java source file that defines remote interface including
remote methods.

2) Implementing remote interface:

It includes writing java source program at server which includes class


implementing remote interface.
3) Writing client that uses remote objects:

The client program obtains a stub for the registry on the server's host, looks up
the remote object's stub by name in the registry, and then invokes the methods
on the remote object using the stub.

4) Implementing server:

A "server" class, in this context, is the class which has a main method that
creates an instance of the remote object implementation, exports the remote
object, and then binds that instance to a name in a Java RMI registry. The class
that contains this main method could be the implementation classes itself or
another class entirely.
5) Compile the source files:

Compile all the source files created.

6) Start RMI registry, server and client.

Practical-

Write a program to implement hello world service using RMI.

Flow of execution of program:

1) hellointerface declares the method printstr().

2) Class helloimpl implements printstr() which outputs the message “hello world”

3) Class helloser creates the remote object and registers it to the RMI registry.

4) Class helloclient performs lookup in the registry stub to obtain the remote object
from the server’s registry. And invokes method printstr() on this object.

Java code is as follows:

// hello world interface


import java.rmi.*;

public interface helloinf extends Remote

public void printstr() throws RemoteException;

//hello world implementation

import java.rmi.*;

import java.rmi.server.UnicastRemoteObject;

public class helloimpl extends UnicastRemoteObject implements helloinf

public void printstr() throws RemoteException

System.out.println("Hello world");

public helloimpl() throws RemoteException

super();

//hello world server

import java.rmi.*;

class helloser

public static void main(String args[]) throws RemoteException

try

helloimpl h=new helloimpl();

Naming.rebind("myhello",h);

System.out.println("server is ready");
}

catch(Exception e)

System.out.println("server failed" + e);

// hello world client

import java.rmi.*;

public class helloclient

public static void main(String args[])

try

helloinf test=(helloinf)Naming.lookup("rmi://localhost/myhello");

test.printstr();

catch(Exception e)

System.out.println("error" + e);

• Output:

Start rmiregistry

• C:\Program Files\Java\jdk1.6.0\bin>start rmiregistry


After starting RMIregistry Run hello world server first , it will give following response.

C:\Program Files\Java\jdk1.6.0\bin>java helloser

server is ready

now run hello client

C:\Program Files\Java\jdk1.6.0\bin>java helloclient

Now go to server prompt again you will get the message from printstr().

C:\Program Files\Java\jdk1.6.0\bin>java helloser

server is ready

Hello world
Practical-

Write a program to implement time service using rmi.

Java code is as follows:

//timeinterface.java-time interface

import java.rmi.*;

public interface timeinterface extends Remote

String gettime() throws RemoteException;

//timeimpl.java-time implementation

import java.rmi.*;

import java.rmi.server.*;

import java.text.*;

import java.util.*;

public class timeimpl extends UnicastRemoteObject implements mytimeinterface

public String gettime() throws RemoteException

Calendar cal=Calendar.getInstance();

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");

return sdf.format(cal.getTime());

public timeimpl() throws RemoteException


{

super();

//timeserver.java-time server

import java.rmi.*;

import java.rmi.registry.*;

public class timeserver

public static void main(String args[])

try

timeimpl obj=new timeimpl();

Naming.rebind("time",obj);

System.out.println("server is ready");

catch(Exception e)

System.out.println("server failed");

//timeclient.java-timeservice client

import java.applet.*;

import java.rmi.Naming;

/*

<applet code="timeclient" height=200 width=200>

</applet>
*/

public class timeclient

public void init()

public static void main(String args[])

try

mytimeinterface t=(mytimeinterface)Naming.lookup("rmi://localhost/time");

System.out.println(t.gettime());

catch(Exception e)

System.out.println("Error" + e);

• Output:

Start rmiregistry.

Run timeser.java, it will give following message

C:\Program Files\Java\jdk1.6.0\bin>java timeserver

server is ready

Now run time client, it will show current time of the system which is returned by
timeserver.
C:\Program Files\Java\jdk1.6.0\bin>java timeclient

04:01:25

C:\Program Files\Java\jdk1.6.0\bin>

Practical-

Write a program to implement calculator service using rmi.

Java code is as follows:

//calcinterface.java-calculator interface

import java.rmi.*;

interface calcinterface extends Remote

public double add(double a,double b) throws RemoteException;

public double sub(double a,double b) throws RemoteException;

public double multi(double a,double b) throws RemoteException;

public double div(double a,double b) throws RemoteException;

//calc.java-calculator implementation

import java.rmi.*;

import java.rmi.server.*;

public class calc extends UnicastRemoteObject implements calcinterface

private String str;

public calc(String msg) throws RemoteException


{

str=msg;

System.out.println("Initializing server");

public double add(double a,double b) throws RemoteException

return a+b;

public double sub(double a,double b) throws RemoteException

return a-b;

public double multi(double a,double b) throws RemoteException

return a*b;

public double div(double a,double b) throws RemoteException

return a/b;

//calcserver.java-calculator server

import java.rmi.Naming;

public class calcserver

public static void main(String args[])

try

Naming.rebind("calci",new calc("calculator"));

System.out.println("server is connected and ready for operation");


}

catch(Exception e)

System.out.println("server not connected" + e);

//calcclient.java-calculator client, implemented using applet

import java.rmi.Naming;

import java.rmi.registry.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="calcclient" height=200 width=200>

</applet>

*/

public class calcclient extends Applet implements ActionListener

Button b1=new Button("+");

Button b2=new Button("-");

Button b3=new Button("*");

Button b4=new Button("/");

Label l1=new Label("Operand1");

Label l2=new Label("Operand2");

Label l3=new Label("Result");

Label ex=new Label(" ");

TextField t1=new TextField(20);

TextField t2=new TextField(20);


TextField t3=new TextField(20);

public void init()

l1.setBounds(20,50,50,20);

add(l1);

l2.setBounds(20,100,50,20);

add(l2);

l3.setBounds(20,150,50,20);

add(l3);

t1.setBounds(150,50,100,20);

add(t1);

t2.setBounds(150,100,100,20);

add(t2);

t3.setBounds(150,150,100,20);

add(t3);

b1.setBounds(20,200,80,20);

add(b1);

b2.setBounds(100,200,80,20);

add(b2);

b3.setBounds(180,200,80,20);

add(b3);

b4.setBounds(260,200,80,20);

add(b4);

ex.setBounds(0,0,110,20);

add(ex);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)

try

if(ae.getSource()==b1)

calcinterface
c=(calcinterface)Naming.lookup("rmi://localhost/calci");

double i=Double.parseDouble(t1.getText());

double j=Double.parseDouble(t2.getText());

double val;

try

val=c.add(i,j);

t3.setText(" " + val);

catch(Exception e)

catch(Exception e)

System.out.println("clientexception" + e);

try

if(ae.getSource()==b2)

calcinterface
c=(calcinterface)Naming.lookup("rmi://localhost/calci");
double i=Double.parseDouble(t1.getText());

double j=Double.parseDouble(t2.getText());

double val;

try

val=c.sub(i,j);

t3.setText(" " + val);

catch(Exception e)

catch(Exception e)

System.out.println("clientexception" + e);

try

if(ae.getSource()==b3)

calcinterface
c=(calcinterface)Naming.lookup("rmi://localhost/calci");

double i=Double.parseDouble(t1.getText());

double j=Double.parseDouble(t2.getText());

double val;

try

val=c.multi(i,j);

t3.setText(" " + val);


}

catch(Exception e)

catch(Exception e)

System.out.println("clientexception" + e);

try

if(ae.getSource()==b4)

calcinterface
c=(calcinterface)Naming.lookup("rmi://localhost/calci");

double i=Double.parseDouble(t1.getText());

double j=Double.parseDouble(t2.getText());

double val;

try

val=c.div(i,j);

t3.setText(" " + val);

catch(Exception e)

}
catch(Exception e)

System.out.println("clientexception" + e);

• Output :

Run rmi registry

Run calculator server, it will give following messages

C:\Program Files\Java\jdk1.6.0\bin>java calcserver

Initializing server

server is connected and ready for operation

run calcclient using appletviewer

C:\Program Files\Java\jdk1.6.0\bin>appletviewer calcclient.java


• Introduction to socket programming:

In client server applications, the server provides some service,such as processing


database quaries or sending out current stock prices. The client uses the service
provided by the server. The communication that occur between the client and server
must be reliable. That is no data can be dropped and it must arrive on the client side
in the same order in which the serevr sent it.

TCP provides a reliable,point-to-point communication channel that client-server


applications on the internet use to communicate with each other. To communicate
over TCP, a client program and a server program establish a connection to one
another. Each program binds a socket to its end of connection. To communicate, the
client and server each reads and writes to the socket bound to the connection.
• What is a socket?

a socket is one end-point of a two-way communication link between two programs


running on the network. Socket classes are used to represent the connection
between a client program and a server program. The java.net package provides two
classes- Socket and ServerSocket that implement the client side of the connection
and the server side of the connection, respectively.

The IPC operations are based on socket pairs, one belonging to a communication
process. IPC is done by exchanging some data through transmitting that data in a
message between a socket in one process and another socket in another process.
When messages are sent, messages are queued at the sending socket until the
underlying network protocol has transmitted them. When they arrive, messages are
queued at receiving socket until the receiving process makes the necessary calls to
receive them.
Practical-

Write a program to implement Echo service using java socket programming

Java code is as follows:

//sampleEchoServer.java - server for echo service

import java.io.*;

import java.net.*;

public class sampleEchoServer

public sampleEchoServer(int portnum)

try

server = new ServerSocket(portnum);

catch (Exception err)

System.out.println(err);

public void serve()

try
{

while (true)

Socket client = server.accept();

BufferedReader r = new BufferedReader(new


InputStreamReader(client.getInputStream()));

PrintWriter w = new PrintWriter(client.getOutputStream(), true);

w.println("Welcome to the Java EchoServer. Type 'bye' to close.");

String line;

do

line = r.readLine();

if ( line != null )

w.println("Got: "+ line);

while ( !line.trim().equals("bye") );

client.close();

catch (Exception err)

System.err.println(err);

public static void main(String[] args)

sampleEchoServer s = new sampleEchoServer(9999);

s.serve();

private ServerSocket server;


}

//sampleEchoClient.java – echo service client

import java.io.*;

import java.net.*;

public class sampleEchoClient

public static void main(String[] args)

try

Socket s=new Socket("127.0.0.1", 9999);

BufferedReader r=new BufferedReader(new


InputStreamReader(s.getInputStream()));

PrintWriter w=new PrintWriter(s.getOutputStream(), true);

BufferedReader con=new BufferedReader(new


InputStreamReader(System.in));

String line;

do

line=r.readLine();

if(line != null)

System.out.println(line);

line=con.readLine();

w.println(line);

while (!line.trim().equals("bye"));

catch (Exception err)

System.err.println(err);

}
}

• Output:

Run sampleEchoServer.java

C:\Program Files\Java\jdk1.6.0>java sampleEchoServer

Now run sampleEchoClient

C:\Program Files\Java\jdk1.6.0\bin>java sampleEchoClient

Welcome to the Java EchoServer. Type 'bye' to close.

hi

Got: hi

hello

Got: hello

bye

C:\Program Files\Java\jdk1.6.0\bin>

You might also like