diff options
Diffstat (limited to 'Year_3')
-rw-r--r-- | Year_3/TSDWL/ex_20191218/MainThread.java | 9 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20191218/Shared.java | 10 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20191218/Thread1.java | 42 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20191218/Thread2.java | 28 |
4 files changed, 89 insertions, 0 deletions
diff --git a/Year_3/TSDWL/ex_20191218/MainThread.java b/Year_3/TSDWL/ex_20191218/MainThread.java new file mode 100644 index 0000000..c340a2a --- /dev/null +++ b/Year_3/TSDWL/ex_20191218/MainThread.java @@ -0,0 +1,9 @@ +public class MainThread { + public static void main(String[] args) { + Shared sh = new Shared(); + Thread1 t1 = new Thread1(sh); + Thread2 t2 = new Thread2(sh); + t1.start(); + t2.start(); + } +} diff --git a/Year_3/TSDWL/ex_20191218/Shared.java b/Year_3/TSDWL/ex_20191218/Shared.java new file mode 100644 index 0000000..105fbf8 --- /dev/null +++ b/Year_3/TSDWL/ex_20191218/Shared.java @@ -0,0 +1,10 @@ +public class Shared { + private int x; + + public Shared() { + x = (int) (Math.random() * (10-0+1)+0); + } + + synchronized void set(int val) { x = val; } + synchronized int get() { return x; } +} diff --git a/Year_3/TSDWL/ex_20191218/Thread1.java b/Year_3/TSDWL/ex_20191218/Thread1.java new file mode 100644 index 0000000..55edaba --- /dev/null +++ b/Year_3/TSDWL/ex_20191218/Thread1.java @@ -0,0 +1,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"); + } + } + } + } +} diff --git a/Year_3/TSDWL/ex_20191218/Thread2.java b/Year_3/TSDWL/ex_20191218/Thread2.java new file mode 100644 index 0000000..35cb3fe --- /dev/null +++ b/Year_3/TSDWL/ex_20191218/Thread2.java @@ -0,0 +1,28 @@ +public class Thread2 extends Thread { + Shared mem; + public Thread2(Shared mem) { + super(); + this.mem = mem; + } + + public void run() { + int m; + + while (true) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + synchronized(mem) { + if (mem.get() == -1) { + break; + } + + System.out.println("\t\t\tThread 2, notify thread 1"); + mem.notify(); + } + } + } +} |