source: liacs/cvp/java/second/RWProblem.java@ 111

Last change on this file since 111 was 2, checked in by Rick van der Zwet, 15 years ago

Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)

File size: 2.0 KB
RevLine 
[2]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 */
8import java.util.Random;
9
10
11
12class 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
30class 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
49class 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
77public 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}
Note: See TracBrowser for help on using the repository browser.