source: liacs/cvp/java/first/RWProblem.java@ 212

Last change on this file since 212 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
11class ReadProcess extends Process
12{
13 public ReadProcess(int number, Database database)
14 {
15 super(number, database);
16 }
17
18 public void run ()
19 {
20 message("Started as READ");
21 database.get_readlock();
22 message("Read: " + database.read());
23 sleep();
24 database.release_writelock();
25 message("Ended");
26 }
27}
28
29class WriteProcess extends Process
30{
31 public WriteProcess(int number, Database database)
32 {
33 super(number, database);
34 }
35
36 public void run ()
37 {
38 message("Started as WRITE");
39 database.get_writelock();
40 database.write(Integer.toString(id));
41 sleep();
42 message("Wrote his Id");
43 database.release_writelock();
44 message("Ended");
45 }
46}
47
48class Process extends Thread
49{
50 protected int id;
51 protected Database database;
52
53 Process (int number, Database d)
54 {
55 this.id = number;
56 database = d;
57 }
58
59 protected void sleep ()
60 {
61 int sleeptime;
62 sleeptime = (int) (Math.random () * 1000);
63 try
64 {
65 Thread.sleep( sleeptime );
66 }
67 catch ( InterruptedException e) { }
68 }
69
70 protected void message (String text)
71 {
72 System.out.println("[" + id + "] " + text);
73 }
74}
75
76public class RWProblem
77{
78 public static void main (String args[])
79 {
80 Database database;
81 int N = 100; //processes
82 int i; //loop counter
83 Random write = new Random();
84
85 database = new Database();
86 Process [] process = new Process [N];
87
88 for( i = 0; i < N; i++)
89 {
90 if (write.nextBoolean())
91 {
92 process[i] = new WriteProcess (i, database);
93 }
94 else {
95 process[i] = new ReadProcess (i, database);
96 }
97 process[i].start();
98 }
99 }
100}
Note: See TracBrowser for help on using the repository browser.