1 | /*
|
---|
2 | * Rick van der Zwet
|
---|
3 | * 0433373
|
---|
4 | * Java programming assigment 1.2
|
---|
5 | * Licence: BSD
|
---|
6 | * $Id: RWProblem.java 270 2007-10-13 13:45:29Z rick $
|
---|
7 | */
|
---|
8 | import java.util.Random;
|
---|
9 |
|
---|
10 |
|
---|
11 |
|
---|
12 | class ReadProcess extends Process
|
---|
13 | {
|
---|
14 | public ReadProcess(int number, Database database)
|
---|
15 | {
|
---|
16 | super(number, database);
|
---|
17 | }
|
---|
18 |
|
---|
19 | public void run ()
|
---|
20 | {
|
---|
21 | message("Started as READ");
|
---|
22 | database.get_readlock();
|
---|
23 | message("Read: " + database.read());
|
---|
24 | sleep();
|
---|
25 | database.release_writelock();
|
---|
26 | message("Ended");
|
---|
27 | }
|
---|
28 | }
|
---|
29 |
|
---|
30 | class WriteProcess extends Process
|
---|
31 | {
|
---|
32 | public WriteProcess(int number, Database database)
|
---|
33 | {
|
---|
34 | super(number, database);
|
---|
35 | }
|
---|
36 |
|
---|
37 | public void run ()
|
---|
38 | {
|
---|
39 | message("Started as WRITE");
|
---|
40 | database.get_writelock();
|
---|
41 | database.write(Integer.toString(id));
|
---|
42 | sleep();
|
---|
43 | message("Wrote his Id");
|
---|
44 | database.release_writelock();
|
---|
45 | message("Ended");
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 | class Process extends Thread
|
---|
50 | {
|
---|
51 | protected int id;
|
---|
52 | protected Database database;
|
---|
53 |
|
---|
54 | Process (int number, Database d)
|
---|
55 | {
|
---|
56 | this.id = number;
|
---|
57 | database = d;
|
---|
58 | }
|
---|
59 |
|
---|
60 | protected void sleep ()
|
---|
61 | {
|
---|
62 | int sleeptime;
|
---|
63 | sleeptime = (int) (Math.random () * 1000);
|
---|
64 | try
|
---|
65 | {
|
---|
66 | Thread.sleep( sleeptime );
|
---|
67 | }
|
---|
68 | catch ( InterruptedException e) { }
|
---|
69 | }
|
---|
70 |
|
---|
71 | protected void message (String text)
|
---|
72 | {
|
---|
73 | System.out.println("[" + id + "] " + text);
|
---|
74 | }
|
---|
75 | }
|
---|
76 |
|
---|
77 | public class RWProblem
|
---|
78 | {
|
---|
79 | public static void main (String args[])
|
---|
80 | {
|
---|
81 | Database database;
|
---|
82 | int N = 100; //processes
|
---|
83 | int i; //loop counter
|
---|
84 | Random write = new Random();
|
---|
85 |
|
---|
86 | database = new Database();
|
---|
87 | Process [] process = new Process [N];
|
---|
88 |
|
---|
89 | for( i = 0; i < N; i++)
|
---|
90 | {
|
---|
91 | if (write.nextBoolean())
|
---|
92 | {
|
---|
93 | process[i] = new WriteProcess (i, database);
|
---|
94 | }
|
---|
95 | else {
|
---|
96 | process[i] = new ReadProcess (i, database);
|
---|
97 | }
|
---|
98 | process[i].start();
|
---|
99 | }
|
---|
100 | }
|
---|
101 | }
|
---|