summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/ex_20191218/Thread1.java
blob: 55edaba872b4e942ffbc07684b9bce112ae5f726 (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
32
33
34
35
36
37
38
39
40
41
42
public class Thread1 extends Thread {
    Shared mem;
    public Thread1(Shared mem) {
        super();
        this.mem = mem;
    }

    public void run() {
        int m;

        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            m = (int) (Math.random() * (10-0+1)+0);

            synchronized(mem) {
                System.out.printf("Thread 1, x = %d, m = %d\n", mem.get(), m);
                if (mem.get() == -1) {
                    break;
                } else if(mem.get() == m) {
                    System.out.println("RISPOSTA CORRETTA");
                    mem.set(-1);
                } else if(Math.abs(m-mem.get()) > 5) {
                    try {
                        System.out.println("risposta MOLTO sbagliata");
                        System.out.println("Thread 1 going to sleep");
                        mem.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                } else {
                    System.out.println("risposta sbagliata");
                }
            }
        }
    }
}