+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

Wei-Lun Hungadd chap. 2 and 3df69975

master
1.0 KiB37 linesraw
1import java.util.Random;
2public class MyThread extends Thread {
3    int myId;
4    Lock lock;
5    Random r = new Random();
6    public MyThread(int id, Lock lock) {
7        myId = id;
8        this.lock = lock;
9    }
10    void nonCriticalSection() {
11        System.out.println(myId + " is not in CS");
12        Util.mySleep(r.nextInt(1000));
13    }
14    void CriticalSection() {
15        System.out.println(myId + " is in CS *****");
16        // critical section code
17        Util.mySleep(r.nextInt(1000));
18    }
19    public void run() {
20        while (true) {
21            lock.requestCS(myId);
22            CriticalSection();
23            lock.releaseCS(myId);
24            nonCriticalSection();
25        }
26    }
27    public static void main(String[] args) throws Exception {
28        MyThread t[];
29        int N = Integer.parseInt(args[0]);
30        t = new MyThread[N];
31        Lock lock = new Bakery(N);//or any other mutex algorithm
32        for (int i = 0; i < N; i++) {
33            t[i] = new MyThread(i, lock);
34            t[i].start();
35        }
36    }
37}