summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/ex_20131219/Thread1.java
blob: b9f8d84c2f3173cb0149fe37ff238d08ba15ecab (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 Thread1 extends Thread {
    private Shared mem;

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

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