The Java Program: Scope.java
1 class Account extends Semaphore {
2 private void check () {
3 if (owner!=Thread.currentThread())
4 throw new IllegalArgumentException ("illegal access");
5 }
6 private int total = 0;
7 public void deposit (int i) { check(); total += 1; }
8 public boolean withdraw (int i) {
9 check ();
10 if (i <= total) { total -= i; return true; }
11 return false;
12 }
13 public int balance () { return total; }
14 }
15
16 class Transaction extends Thread {
17 private static Account accounts [] = new Account [100];
18 static {
19 for (int i=0;i<accounts.length;i++) {accounts[i]=new Account();}
20 }
21
22 private Account a;
23 Transaction (int no) { a = accounts[no]; }
24
25 public void run () {
26 try {
27 a.lock(); // acquire exclusive accesss to account
28 // get amount, etc
29 int d = 100;
30 // withdraw amount (if possible)
31 if (a.withdraw(d)) {
32 }
33 System.out.println (a.balance());
34 // dispense receipt, etc
35 } finally {
36 a.unlock(); // be sure to relinquish lock
37 }
38 }
39 }
40
41 public class Scope {
42 public static void main (String args[]) {
43 new Transaction (3).start();
44 new Transaction (3).start();
45 }
46 }