print - java(old format)

26
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.

Upload: nirav-suthar

Post on 04-Apr-2015

44 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Print - Java(Old Format)

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.

Page 2: Print - Java(Old Format)

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.javaimport 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();

Page 3: Print - Java(Old Format)

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) { } } }

Page 4: Print - Java(Old Format)

} 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 PCpress ctrl-c to stopput:0got:0put:1got:1put:2got:2put:3got:3

Page 5: Print - Java(Old Format)

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;

Page 6: Print - Java(Old Format)

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

Page 7: Print - Java(Old Format)

{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

}

}

output:

enter 3 stringswelcometoldenggcollege

thread name:Thread-0 -- length=7thread name:Thread-2 -- length=13thread name:Thread-1 -- length=2C:\Program Files\Java\jdk1.6.0\bin>

Page 8: Print - Java(Old Format)

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 includesunmarshal the parameter for the remote methodInvoke the methodMarshal 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.

Page 9: Print - Java(Old Format)

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.*;

Page 10: Print - Java(Old Format)

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)

{

Page 11: Print - Java(Old Format)

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 helloserserver is ready

now run hello clientC:\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 helloserserver is readyHello world

Page 12: Print - Java(Old Format)

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 implementationimport 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 serverimport 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) {

Page 13: Print - Java(Old Format)

System.out.println("server failed"); }}}//timeclient.java-timeservice clientimport 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 timeserverserver 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 timeclient04:01:25

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

Page 14: Print - Java(Old Format)

Practical-Write a program to implement calculator service using rmi.

Java code is as follows:

//calcinterface.java-calculator interfaceimport 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 implementationimport 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 serverimport java.rmi.Naming;public class calcserver{ public static void main(String args[]) { try { Naming.rebind("calci",new calc("calculator"));

Page 15: Print - Java(Old Format)

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 appletimport 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);

Page 16: Print - Java(Old Format)

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)

Page 17: Print - Java(Old Format)

{ } } } 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) { } } }

Page 18: Print - Java(Old Format)

catch(Exception e) { System.out.println("clientexception" + e); } } }

Output :Run rmi registryRun calculator server, it will give following messages

C:\Program Files\Java\jdk1.6.0\bin>java calcserverInitializing serverserver 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:

Page 19: Print - Java(Old Format)

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-

Page 20: Print - Java(Old Format)

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.");

Page 21: Print - Java(Old Format)

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 clientimport 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);

Page 22: Print - Java(Old Format)

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 sampleEchoClientWelcome to the Java EchoServer. Type 'bye' to close.hiGot: hihelloGot: hellobye

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