summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/ex_20131219/Thread2.java
blob: 152e9e037fe87eaba13418b726eeb66cae29e242 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Thread2 extends Thread {
    private Shared mem;

    public Thread2(Shared mem) {
        super();
        this.mem = mem;
    }

    public void run() {
        int xrand;
        int m;
        while (true) {
            synchronized(mem) {
                m = mem.get();
                if (m >= 6 && m <= 10) {
                    xrand = (int) (Math.random() * (10-1+1)+1);
                    System.out.printf("\t\t\tThread 2: (%d, %d)\n", m, xrand);
                    mem.set(xrand);
                    mem.notifyAll();
                } else {
                    try {
                        mem.wait();
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }
    }
}