Professional Documents
Culture Documents
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.
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:
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.
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.
//PC.java
import java.io.*;
class Q
while(set==false)
try
wait();
catch(InterruptedException e)
System.out.println("got:" +n);
set=false;
notify();
return n;
while(set==true)
try
wait();
catch(InterruptedException e)
}
System.out.println("put:" +n);
this.n=n;
set=true;
notify();
Q q;
int num;
producer(Q q)
this.q=q;
new Thread(this,"producer").start();
int i=0;
while(true)
q.put(i++);
try {
T Thread.sleep(1000);
catch(InterruptedException e)
}
}
Q q;
consumer(Q q)
this.q=q;
new Thread(this,"consumer").start();
while(true)
q.get();
try {
Thread.sleep(1000);
catch(InterruptedException e)
class PC
{
public static void main(String args[])
Q q=new Q();
new producer(q);
new consumer(q);
Program Files\Java\jdk1.6.0\bin>java PC
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-
1) Main () takes three strings as input from the user and creates three threads of
execution.
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.
import java.io.*;
import java.util.Scanner;
class called
try
Thread.sleep(1000);
catch(Exception e)
System.out.println("Interrupt");
return m.length();
String s;
called a;
Thread t;
a=tar;
s=str;
t=new Thread(this);
t.start();
String thrdnm;
int i=a.len(s);
thrdnm=t.getName();
String str1,str2,str3;
System.out.println("enter 3 strings");
str1=s.nextLine();
str2=s.nextLine();
str3=s.nextLine();
try
ob1.t.join();
ob2.t.join();
ob3.t.join();
catch(InterruptedException e)
System.out.println("Interrupted");
}
}
• output:
enter 3 strings
welcome
to
ldenggcollege
C:\Program Files\Java\jdk1.6.0\bin>
• Introduction to java RMI:
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.
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.
It includes creating a java source file that defines remote interface including
remote methods.
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:
Practical-
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.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
System.out.println("Hello world");
super();
import java.rmi.*;
class helloser
try
Naming.rebind("myhello",h);
System.out.println("server is ready");
}
catch(Exception e)
import java.rmi.*;
try
helloinf test=(helloinf)Naming.lookup("rmi://localhost/myhello");
test.printstr();
catch(Exception e)
System.out.println("error" + e);
• Output:
Start rmiregistry
server is ready
Now go to server prompt again you will get the message from printstr().
server is ready
Hello world
Practical-
//timeinterface.java-time interface
import java.rmi.*;
//timeimpl.java-time implementation
import java.rmi.*;
import java.rmi.server.*;
import java.text.*;
import java.util.*;
Calendar cal=Calendar.getInstance();
return sdf.format(cal.getTime());
super();
//timeserver.java-time server
import java.rmi.*;
import java.rmi.registry.*;
try
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>
*/
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.
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-
//calcinterface.java-calculator interface
import java.rmi.*;
//calc.java-calculator implementation
import java.rmi.*;
import java.rmi.server.*;
str=msg;
System.out.println("Initializing server");
return a+b;
return a-b;
return a*b;
return a/b;
//calcserver.java-calculator server
import java.rmi.Naming;
try
Naming.rebind("calci",new calc("calculator"));
catch(Exception e)
import java.rmi.Naming;
import java.rmi.registry.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
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);
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);
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);
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);
catch(Exception e)
}
catch(Exception e)
System.out.println("clientexception" + e);
• Output :
Initializing server
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-
import java.io.*;
import java.net.*;
try
System.out.println(err);
try
{
while (true)
String line;
do
line = r.readLine();
if ( line != null )
while ( !line.trim().equals("bye") );
client.close();
System.err.println(err);
s.serve();
import java.io.*;
import java.net.*;
try
String line;
do
line=r.readLine();
if(line != null)
System.out.println(line);
line=con.readLine();
w.println(line);
while (!line.trim().equals("bye"));
System.err.println(err);
}
}
• Output:
Run sampleEchoServer.java
hi
Got: hi
hello
Got: hello
bye
C:\Program Files\Java\jdk1.6.0\bin>