Professional Documents
Culture Documents
No:01
Date:18/02/10
Algorithm:
* Assume there are three processes: Pa, Pb, and Pc. Only Pa can output
* the letter A, Pb B, and Pc C.
* Utilizing only semaphores (and no other variables) the processes are
* synchronized so that the output satisfies the following conditions:
* a) A B must be output before any C's can be output.
* b) B's and C's must alternate in the output string, that is, after the
*
is output.
* c) The total number of B's and C's which have been output at any given
*
point in the output string cannot exceed the number of A's which have
* Examples
* AACB
-- invalid, violates a)
* ABACAC
-- invalid, violates b)
* AABCABC
* AABCAAABC
* AAAABCBC
-- invalid, violates c)
-- valid
-- valid
* AB
-- valid
*/
An Algorithm For More Than Two Processes:/* Entry section for P1 */ /* Entry section for P2 */
Q1 := True; Q2 := True;
TURN := 1; TURN := 2;
wait while Q2 and TURN := 1; wait while Q1 and TURN := 2;
/* Exit section for P1 */ /* Exit section for P2 */
Q1 := False; Q2 := False;
Both in this algorithm and in all of the previous ones, the processes busy-wait
until they are allowed to enter the critical section. One might wonder why these
algorithms busy-wait instead of simply context-switching to another ready process. At
the beginning of this paper, we made the assumption that critical sections were usually
very small; this would imply that any process busy-waiting on a lock would likely
wait for a fairly short period of time. The overhead of context-switching is usually
large enough that busy-waiting is more efficient. For critical sections that are longer,
such as those with disk access, the above algorithms can be used as low-level building
blocks for higher-level semaphores.
PROGRAM: ABCs.java
import java.io.Serializable;
import java.util.Date;
import java.util.Random;
class BinarySemaphore {
private boolean locked = false;
BinarySemaphore() {} // constructors
BinarySemaphore(boolean initial) {locked = initial;}
BinarySemaphore(int initial) {locked = (initial == 0);}
public synchronized void P() {
while (locked) {
try {
wait();
} catch (InterruptedException e) {
}}
locked = true;
}
public synchronized void V(){
if (locked) notify();
locked = false;
}}
3
class CountingSemaphore {
private int value = 0;
private int waitCount = 0;
private int notifyCount = 0;
public CountingSemaphore(int initial){
if (initial > 0) value = initial;
}
public synchronized void P() {
if (value <= waitCount) {
waitCount++;
try {
do {
wait();
} while (notifyCount == 0);
} catch(InterruptedException e) {
notify();
} finally {
waitCount--;
}
notifyCount--;
}
value--;
}
public synchronized void V() {
value++;
if (waitCount > notifyCount) {
4
notifyCount++;
notify();
}
}}
class Pa extends ABCs implements Runnable { // extend ABCs to
// access semaphore sum
public void run () {
while (true) { nap(1+(int)(random(500)));
System.out.print("A"); System.out.flush();
try {
V(sum);
} catch (Exception e){}
}
}}
class Pb extends ABCs implements Runnable {
public void run () {
while (true) { nap(1+(int)(random(800)));
P(C); P(sum);
System.out.print("B"); System.out.flush();
V(B);
}
}}
class Pc extends ABCs implements Runnable {
public void run () {
while (true) { nap(1+(int)(random(800)));
P(B); P(sum);
5
System.out.print("C"); System.out.flush();
V(C);
}
}}
class ABCs {
protected static final BinarySemaphore B
= new BinarySemaphore(0);
// these semaphores
// are static
// so subclasses
// Pa, Pb,
// them
OUT PUT:-
Result:
Thus the given program was coded and executed successfully.
Ex.No:02
Date:25/02/10
Problem Description:Consider a system with three smoker processes and one agent process. Each
smoker continuously rolls a cigarette and then smokes it. But to roll and smoke a
cigarette, the smoker needs three ingredients: tobacco, paper, and matches. One of the
smoker processes has paper, another has tobacco, and the third has matches. The agent
has an infinite supply of all three materials. The agent places two of the ingredients on
the table. The smoker who has the remaining ingredient then makes and smokes a
cigarette, signaling the agent on completion. The agent then puts out another two of
the three ingredients, and the cycle repeats.
Agent.java
import java.util.*;
public class Agent extends Thread
{
private Table table;
private Random rand;
public Agent(Table tab,String name)
{
super(name);
table=tab;
rand=new Random();
}
11
case 0: table.put(Table.Tobacco_Paper);
break;
case 1: table.put(Table.Paper_Matches);
break;
case 2: table.put(Table.Matches_Tobacco);
break;
}}
}}
Smoker .java
import java.util.*;
public class Smoker extends Thread
{
private Table table;
private Random rand;
private int needs;
public Smoker(Table tab,String name,int what)
{
super(name);
table=tab;
rand=new Random();
12
needs=Table.Everything^what;
}
public void run()
{
while(true)
try
{
table.get(needs);
System.out.println(getName()+":Rolling.");
sleep(Math.abs(rand.nextInt())%1000);
System.out.println(getName()+":Smoking.");
sleep(Math.abs(rand.nextInt())%1000);
System.out.println(getName()+":Done Smoking.");
table.DoneSmoking();
}
catch(InterruptedException e){}
}
}}
Table.java
import java.util.*;
public class Table
{public static final int Nothing=0;
public static final int Tobacco=1;
public static final int Paper=2;
public static final int Matches=4;
public static final int Tobacco_Paper=Tobacco+Paper;
public static final int Paper_Matches=Paper+Matches;
13
while((contains&what)!=what)
try
{
System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"No!");
wait();
}
catch(InterruptedException e){}
14
}
System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"Yes!");
contains=contains^what;
}
public synchronized void DoneSmoking()
{
notifyAll();
}
public String contains(int what)
{
String s="";
if((what&Tobacco)==Tobacco)
s=s+"tobacco";
if((what&Paper)==Paper)
s=s+"paper";
if((what&Matches)==Matches)
s=s+"matches";
return s;
}}
TableCS.java
import java.util.*;
public class TableCS extends Table{
TableCS Table;
}
Cigarette.java
import java.util.*;
15
OUTPUT:
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccomatches
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 1:gettingtobaccomatches-Yes!
Smoker 1:Rolling.
16
Smoker 1:Smoking.
Smoker 1:Done Smoking.
Smoker 1:gettingtobaccomatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Agent:puttingtobaccopaper
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-Yes!
Smoker 2:Rolling.
Smoker 1:gettingtobaccomatches-No!
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccopaper
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-Yes!
Smoker 1:gettingtobaccomatches-No!
Smoker 2:Rolling.
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccomatches
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-Yes!
Smoker 1:Rolling.
Smoker 1:Smoking.
Smoker 1:Done Smoking.
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 1:gettingtobaccomatches-No!
17
Result:
Thus the given program was coded and executed successfully.
Ex.No:03
Date:04/03/10
Aim:
18
PROBLEM DESCRIBTION:-
ALGORITHM:
PROGRAM :
Semaphore.java:
20
SleepingBarber.java
class Semaphore extends Object
21
{
private int count;
public Semaphore(int startingCount){
count = startingCount;
}
public void down(){
synchronized (this) {
while (count <= 0) {
try {
wait();
} catch (InterruptedException ex) {
}}
count--;
}}
public void up(){
synchronized (this) {
count++;
if (count == 1 ) {
notify();
}}
}}
public class SleepingBarber extends Thread {
public static Semaphore customers = new Semaphore(0);
public static Semaphore barbers = new Semaphore(0);
public static Semaphore mutex = new Semaphore(1);
public static int waiting = 0;
22
SleepingBarberD.java
class Semaphore extends Object
{
private int count;
public Semaphore(int startingCount){
count = startingCount;
}
public void down(){
synchronized (this) {
while (count <= 0) {
try {
wait();
} catch (InterruptedException ex) {
25
}}
count--;
}}
public void up(){
synchronized (this) {
count++;
if (count == 1 ) {
notify();
}}
}}
public class SleepingBarberD extends Thread {
public static Semaphore customers = new Semaphore(0);
public static Semaphore barbers = new Semaphore(0);
public static Semaphore mutex = new Semaphore(1);
public static int waiting = 0;
public static final int CHAIRS = 5;
class Barber extends Thread {
private int myNumber;
public Barber(int i) {
myNumber = i;
}
public void run(){
while(true) {
customers.down();
mutex.down();
waiting = waiting - 1;
26
barbers.up();
mutex.up();
cut_hair();
}}
public void cut_hair(){
System.out.println("Barber " + myNumber + " is cutting hair");
try {
sleep(7500);
} catch (InterruptedException ex){ }
}}
private class Customer extends Thread {
private int myNumber;
public Customer(int i) {
myNumber = i;
}
public void run(){
mutex.down();
if(waiting < CHAIRS){
waiting = waiting + 1;
customers.up();
mutex.up();
try { //random sleep
sleep(10000);
} catch (InterruptedException e) {}
try {
sleep(10000);
27
} catch (InterruptedException e) {}
try {
sleep(10000);
} catch (InterruptedException e) {}
barbers.down();
get_haircut();
} else {
mutex.up();
}}
public void get_haircut(){
System.out.println("Customer " + myNumber
+ " is getting his hair cut");
try {
sleep(10000);
} catch (InterruptedException ex){ }
}}
public static void main(String args[]) {
SleepingBarberD holder = new SleepingBarberD();
holder.start();
}
public void run(){
final int BARBERS = 3;
Barber aBarber;
Customer aCustomer;
for(int i=0; i<3;i++)
{
28
29
31
Result:
Thus the given program was coded and executed successfully.
Ex.No:04
Date:19/03/10
File transfers;
Network games.
Network architecture
To create an RJ45 local area network, it is recommended that you adopt a so-called
"star" structure, where the computers are each connected to the hub via an RJ45 cable.
A hub is a device that transfers data from one computer to another. The choice of hub
will be made in function of the number of connected computers in order to have
enough plugs (called "ports") on the hub.
In the event of a large network or a network with substantial bandwidth requirements,
a switch will favourably replace the hub, as it makes it possible to distribute packets
only to the computers concerned, whereas a hub systematically sends packets to all
connected computers.
The structure of such a network looks like this:
If you want to connect two computers only, it is possible to avoid using a hub, by
directly connecting the two computers with a crossover RJ45 cable.
33
WakeOnLan.java
import java.io.*;
import java.net.*;
public class WakeOnLan {
public static final int PORT = 9;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java WakeOnLan <broadcast-ip> <mac-address>");
System.out.println("Example: java WakeOnLan 172.15.169.7 00-15-58-A3-4F-20");
System.out.println("Example: java WakeOnLan 172.15.169.8 00-15-58-A3-0C-27");
System.exit(1);
}
String ipStr = args[0];
String macStr = args[1];
try {
byte[] macBytes = getMacBytes(macStr);
byte[] bytes = new byte[6 + 16 * macBytes.length];
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) 0xff;
}
for (int i = 6; i < bytes.length; i += macBytes.length) {
System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
}
InetAddress address = InetAddress.getByName(ipStr);
34
35
36
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}
return bytes;
}}
37
38
OUTPUT
D:\Java\jdk1.5.0_06\bin>javac WakeOnLan.java
D:\Java\jdk1.5.0_06\bin>java WakeOnLan 172.15.169.8 00-15-58-A3-0C-27
Wake-on-LAN packet sent.
Result:
Thus the given program was coded and executed successfully.
39
40
Ex.No:05
Date:26/03/10
Aim:
To write a real-time program implementing an alarm clock .
PROBLEM DESCRIPTION:A clock with alarm functionality shall be implemented. It shall be possible to
set the time. It shall be possible to set the alarm time. The alarm shall be enabled when
the alarm time is set. The alarm shall be activated when the alarm is enabled, and
when the current time is equal to the alarm time. An activated alarm must be
acknowledged. Acknowledgement of an alarm shall lead to the alarm being disabled.
The alarm is enabled again when a new alarm time is set. An alarm which is not
acknowledged shall be repeated every 10 seconds. The program shall communicate
with a graphical user interface, where the current time shall be displayed, and where
the alarm time shall be displayed when the alarm is enabled. It shall be possible to
terminate the program, using a command which is sent from the graphical user
interface.
ALGORITHM:
Display init is used for initialization, and shall be called from the main
function of the program, before the processes are created.
Display time displays the current time, and shall be called by the clock
process.
Display alarm time shows the current alarm time, and shall be called when a
new alarm time is set.
Erase alarm time erases the displayed alarm time, and shall be called when the
user acknowledges an alarm.
Display alarm text is used to show an alarm activation, and shall be called
when the user shall be informed that the alarm has been activated,i.e. when the
alarm is activated the first time, and when the alarm is activated repeatedly
(which is every 10 seconds, according to the above stated requirments).
Erase alarm text erases the information displayed by display alarm text, and
shall be called when the user acknowledges an alarm.
41
PROGRAM:#include<stdio.h>
#include<conio.h>
#include<dos.h>
struct clk
{
int hh,mm,ss;
}c1,c2;
void clock(int *h1,int *m1,int *s1)
{
*s1=*s1+1;
if(*s1==60)
{
*s1=0; *m1=*m1+1;
if(*m1==60)
{
*m1=0;*h1=*h1+1;
if(*h1==24)
*h1=0;
}
}}
void timer(int *h,int *m,int *s)
42
{
if((*s)!=0)
{
*s=*s-1;
}
else if((*s)==0)
{
if(*m!=0)
{
*s=59;*m=*m-1;
}
else if(*m==0)
{
if(*h!=0)
{
*m=59;*h=*h-1;
}
}
}}
void alarm()
{
int i;
while(!kbhit())
{
for(i=0;i<2;i++)
{
sound(5000);
43
delay(100);
nosound();
delay(200);
}
delay(500);
}}
void main()
{
char ch;
struct time t;
clrscr();
printf("\nPress:-\n\tA: for alarm Clock\n\tT: for Timer\n");
printf("\Enter your Choice:");
ch=getche();
switch (ch)
{
case 'A':
case 'a':
{
printf("\n\n\n24 hr Format(HH:MM:SS)");
gettime(&t);
c1.hh=t.ti_hour; c1.mm=t.ti_min; c1.ss=t.ti_sec;
printf("\nEnter alarm time : ");
scanf("%d:%d:%d",&c2.hh,&c2.mm,&c2.ss);
if(c2.hh>24||c2.mm>60||c2.ss>60)
{
44
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t");
printf("%02d:%02d:%02d",c1.hh,c1.mm,c1.ss);
timer(&c1.hh,&c1.mm,&c1.ss);
delay(1000);
}
clrscr();
printf("Program Written by: Anshu Krishna\n");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t");
printf("00:00:00");
alarm();
exit(0);
}
break;
default:
{
printf("\n\tInvalid Input\n\n\tPlease restart the program");
delay(2500);exit(0);
}
}}
46
OUTPUT:
47
48
49
Result:
Thus the given program was coded and executed successfully.
Ex.No:06
Date:05/04/10
50
Transaction
Object
ClientsTransaction
SchedulerObject Objects
managerObjects
Scheduler
Clients manager
manager
manager
ALGORITHM:-
(i)
(ii)
(iii)
(iv)
Reducing the chance of the preconditions being invalid reduces the chance of
optimistic failure.
Try to change arbitrary data into either predictable reference data or into
personal data to achieve the second.
For predictable reference data we do not have to design for issues caused by
concurrent change; we can just assume it will never happen, and that it is not worth
the effort to design elaborate exception handling.
For arbitrary data we have to design for exceptions caused by concurrent change.
When we use arbitrary data, we accept the chance that we will have to tell the user
51
that we encountered a concurrency issue. We accept that we will have to tell the user
that the transaction was rejected, or that we have to ask the user for a resolution. We
may have to design how to turn arbitrary data into predictable reference data, and also
design for multiple validity periods of specific information, such as an address change.
Arbitrary data may be problematic, and we should try to avoid using it as a
precondition. That is, we should try to avoid using arbitrary data to formulate requests
to the service, and avoid using it to support the users' decisions.
For personal data we can accept exceptions, because they're easy to explain to the
user, and should be expected. (The user caused them in the first place, for instance, by
making offline changes on two systems.)
Almost all recommendations in this article concern the design of the service
interaction, and can thus be formulated as recommendations for good service design.
Design postings
52
53
When a sub transaction aborts then all of its steps are undone, including any of
its sub transactions. However, this does not cause the abort of the parent
transaction; instead the parent transaction is simply notified of the abort.
When a sub transaction is executing the entities that it is updating are not
visible to other transactions or sub transactions (as per the isolation property).
When a sub transaction commits then the updated entities are made visible to
other transactions and sub transactions.
54
Program:
CLIENT
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
public class client
{
{
try
{
Socket s=new Socket("172.15.169.3",8080);
try
{
DataOutputStream out=new DataOutputStream(s.getOutputStream());
DataInputStream in=new DataInputStream(s.getInputStream());
out.writeInt(25);
while(true)
{
System.out.println("=========================================");
55
case 1:
try
{
acno1=sc.nextInt();
b1=true;
}catch(Exception e)
{
System.out.println("Enter the Account Number Correctly");
}
out.writeBoolean(b1);
if(b1== true)
{
out.writeUTF(name);
out.writeInt(acno1);
}
break;
case 2:
System.out.print("Enter the Account Number:");
int acno=0;
boolean pach=false;
try
{
acno=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Enter the Valid Account Number");
pach=true;
}
57
int bal=0;
out.writeInt(acno);
if(in.readBoolean())
{
bal=in.readInt();
System.out.println("the Balance is:"+bal);
}
else
{
if(pach==false)
{
System.out.println("Account not available");
}
}
break;
case 3:
boolean check1=false;
int acno3=0;
int amt3=0;
try
{
System.out.print("Enter the Account Number:");
acno3=sc.nextInt();
System.out.print("Enter the Ammount:");
amt3=sc.nextInt();
}
58
catch(Exception e)
{
System.out.println("Invalid Input");
check1=true;
}
if(check1==false)
{
out.writeInt(acno3);
out.writeInt(amt3);
if(in.readBoolean())
{
if(in.readBoolean())
{
System.out.println("Money is Withdrawn");
}
else
{
System.out.println("Money is not Enough to Withdraw");
}
}
else
{
System.out.println("Account is not available");
break;
}
}
59
break;
case 4:
System.out.print("Enter the Account Number:");
int acno4=sc.nextInt();
out.writeInt(acno4);
System.out.print("Enter the Ammount:");
int amt4=sc.nextInt();
out.writeInt(amt4);
if(in.readBoolean())
{
System.out.println("Ammount is Deposited");
}
else
{
System.out.println("Check the Account Number");
}
break;
case 5:
System.out.print("Enter the From Account:");
int tac1=sc.nextInt();
out.writeInt(tac1);
System.out.print("Enter the To Account:");
int tac2=sc.nextInt();
out.writeInt(tac2);
System.out.print("Enter the Amount to transfer:");
int tamt=sc.nextInt();
60
out.writeInt(tamt);
break;
case 6:
System.exit(0);
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
finally
{
s.close();
}
}catch(IOException e)
{
e.printStackTrace();
}}}
SERVER
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import java.lang.*;
61
try
while(true)
{
Socket incoming=s.accept();
Runnable r=new bankserver(incoming);
Thread t=new Thread(r);
t.start();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}}
class bankserver implements Runnable
{
public bankserver(Socket i)
{
incoming=i;
}
public void run()
{
try
62
try
{
DataOutputStream out=new DataOutputStream(incoming.getOutputStream());
DataInputStream in=new DataInputStream(incoming.getInputStream());
System.out.println(in.readInt());
while(true)
{
int choice=in.readInt();
System.out.println("You have selected choice"+choice);
switch(choice)
{
case 1:
String name=null;
int acno1=0;
if(in.readBoolean())
{
name=in.readUTF();
acno1=in.readInt();
}
else
{
break;
}
int a=0;
try
{
63
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
Statement st=con.createStatement();
String str1="insert into parthi values('"+name+"','"+acno1+"','"+a+"')";
st.executeUpdate(str1);
}
catch(Exception e)
{
System.out.println("Account Number is already allocated");
}
break;
case 2:
int acno=in.readInt();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno;
System.out.println(s1);
int bal=0;
ResultSet rs=st.executeQuery(s1);
boolean check=true;
String name2=null;
while(rs.next())
{
64
name2=rs.getString(1);
bal=rs.getInt(3);
}
if(name2==null)
{
check=false;
out.writeBoolean(check);
}
else
{
out.writeBoolean(check);
out.writeInt(bal);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 3:
int acno3=in.readInt();
int amt3=in.readInt();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
65
Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno3;
System.out.println(s1);
int bal=0;
ResultSet rs=st.executeQuery(s1);
String name3=null;
boolean check3=true;
while(rs.next())
{
bal=rs.getInt(3);
name3=rs.getString(1);
}
if(name3== null)
{
check3=false;
}
boolean chstatus=false;
if(bal>0 && bal>amt3)
{
Object lock2=new Object();
synchronized(lock2)
{
int tmp=bal-amt3;
String s2="update parthi set balance="+tmp+" where accnumber="+acno3;
System.out.println(s2);
st.executeUpdate(s2);
chstatus=true;
66
}
}
else
{
System.out.println("Money not Ennough");
}
out.writeBoolean(check3);
if(check3==true)
{
out.writeBoolean(chstatus);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 4:
int acno4=in.readInt();
int amt4=in.readInt();
System.out.println(acno4);
System.out.println(amt4);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
67
Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno4;
System.out.println(s1);
String name1=null;
ResultSet rs=st.executeQuery(s1);
while(rs.next())
{
name1=rs.getString(1);
}
System.out.println(name1);
boolean ch=false;
if(name1!=null)
{
System.out.println("hai");
int actmp=0;
ResultSet rs1=st.executeQuery(s1);
while(rs1.next())
{
actmp=rs1.getInt(3);
}
System.out.println(actmp);
Object lock1=new Object();
synchronized(lock1)
{
int tmpbal=actmp+amt4;
String s2="update parthi set balance="+tmpbal+" where accnumber="+acno4;
68
System.out.println(s2);
st.executeUpdate(s2);
}
ch=true;
out.writeBoolean(ch);
}
else
{
System.out.println("nO rECORD");
out.writeBoolean(ch);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 5:
int tac1=in.readInt();
int tac2=in.readInt();
int tamt=in.readInt();
System.out.println(tac1+"
"+tac2+"
"+tamt);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
69
Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+tac1;
String s2="Select * from parthi where accnumber="+tac2;
System.out.println(s1);
System.out.println(s2);
ResultSet rs1=st.executeQuery(s1);
int bal1=0;
while(rs1.next())
{
bal1=rs1.getInt(3);
}
ResultSet rs2=st.executeQuery(s2);
int bal2=0;
while(rs2.next())
{
bal2=rs2.getInt(3);
}
if(bal1 < tamt)
{
}
else
{
synchronized(lock)
{
bal1=bal1-tamt;
bal2=bal2+tamt;
70
e.printStackTrace();
}
break;
case 6:
System.out.println("Client is exit");
break;
default:
System.out.println("Invalid Input from client");
break;
}
}}
catch(Exception e)
{
System.out.println("Client is Disconnected");
}
finally
{
incoming.close();
}}
71
catch(IOException e)
{
e.printStackTrace();
}
}}
OUTPUT :
72
73
74
75
Result:
Thus the given program was coded and executed successfully.
Ex.No:07
Date:12/04/10
Aim:
To Design a RMI Lottery application.
Alorithm:
Design a superimposed computation which detects that there exists an
interleaving of underlying events in this system where at some state P ^Q
holds. (A superposed computation is one that does not a_ect the underlying
system; it may \read" but not \write" the state of the underlying system. Events
in a superposed computation may occur in at the same instant as the underlying
events and/or at di_erent instants.) State any assumptions you make.
76
Program:
LottoMad.java
import java.awt.*;
import java.net.*;
public class LottoMad1 extends java.applet.Applet
implements Runnable {
Thread playing;
// set up row 1
Panel row1 = new Panel();
CheckboxGroup option = new CheckboxGroup();
Checkbox quickpick = new Checkbox("Quick Pick", option, false);
Checkbox personal = new Checkbox("Personal",option, true);
// set up row 2
77
setBackground(Color.lightGray);
GridLayout appletLayout = new GridLayout(5, 1, 10, 10);
setLayout(appletLayout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(layout1);
row1.add(quickpick);
row1.add(personal);
add(row1);
stop.enable(false);
reset.enable(false);
row3.add(stop);
row3.add(play);
row3.add(reset);
add(row3);
row4.add(years);
add(row4);
}
stop.enable(false);
reset.enable(true);
quickpick.enable(false);
personal.enable(false);
for (int i = 0; i < 6; i++) {
numbers[i].setEditable(false);
}
playing.stop();
playing = null;
}
}
if (event.target instanceof Checkbox) {
if (event.target.equals(quickpick)) {
for (int i = 0; i < 6; i++) {
int pick;
do {
pick = (int)Math.floor(Math.random() * 50 + 1);
} while (numberGone(pick, numbers, i));
numbers[i].setText("" + pick);
}
} else {
for (int i = 0; i < 6; i++)
numbers[i].setText(" ");
}
}
return true;
82
void clearAllFields() {
for (int i = 0; i < 6; i++) {
numbers[i].setText("");
winners[i].setText("");
}
got3.setText("0");
got4.setText("0");
got5.setText("0");
got6.setText("0");
drawings.setText("0");
years.setText("0");
}
playing.stop();
playing = null;
clearAllFields();
}
boolean numberGone(int num, TextField[] pastNums, int count) {
for (int i = 0; i < count; i++)
if (Integer.parseInt(pastNums[i].getText()) == num)
return true;
return false;
}
84
int matches = 0;
for (int i = 0; i < 6; i++) {
int ball;
do {
ball = (int)Math.floor(Math.random() * 50 + 1);
} while (numberGone(ball, winners, i));
winners[i].setText("" + ball);
if (matchedOne(winners[i], numbers))
matches++;
}
switch (matches) {
case 3:
addOneToField(got3);
break;
case 4:
addOneToField(got4);
break;
case 5:
addOneToField(got5);
break;
case 6:
addOneToField(got6);
stop.enable(false);
play.enable(true);
reset.enable(true);
playing.stop();
85
}
try { Thread.sleep(100); }
catch (InterruptedException e) {}
}
}
}
OUTPUT
86
Result:
Thus the given program was coded and executed successfully.
87