diff options
-rw-r--r-- | Year_3/TSDWL/ex_20131219/MainThread.java | 17 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20131219/Shared.java | 10 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20131219/Thread1.java | 31 | ||||
-rw-r--r-- | Year_3/TSDWL/ex_20131219/Thread2.java | 31 |
4 files changed, 89 insertions, 0 deletions
diff --git a/Year_3/TSDWL/ex_20131219/MainThread.java b/Year_3/TSDWL/ex_20131219/MainThread.java new file mode 100644 index 0000000..ea62871 --- /dev/null +++ b/Year_3/TSDWL/ex_20131219/MainThread.java @@ -0,0 +1,17 @@ +public class MainThread { + public static void main(String[] args) { + Shared mem = new Shared(); + Thread1 t1 = new Thread1(mem); + Thread2 t2 = new Thread2(mem); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/Year_3/TSDWL/ex_20131219/Shared.java b/Year_3/TSDWL/ex_20131219/Shared.java new file mode 100644 index 0000000..18976c5 --- /dev/null +++ b/Year_3/TSDWL/ex_20131219/Shared.java @@ -0,0 +1,10 @@ +public class Shared { + private int m; + + public Shared() { + m = (int) (Math.random() * (11-1+1)+1); + } + + synchronized public void set(int val) { m = val; } + synchronized public int get() { return m; } +} diff --git a/Year_3/TSDWL/ex_20131219/Thread1.java b/Year_3/TSDWL/ex_20131219/Thread1.java new file mode 100644 index 0000000..b9f8d84 --- /dev/null +++ b/Year_3/TSDWL/ex_20131219/Thread1.java @@ -0,0 +1,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; + } + } + } + } + } +} diff --git a/Year_3/TSDWL/ex_20131219/Thread2.java b/Year_3/TSDWL/ex_20131219/Thread2.java new file mode 100644 index 0000000..152e9e0 --- /dev/null +++ b/Year_3/TSDWL/ex_20131219/Thread2.java @@ -0,0 +1,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; + } + } + } + } + } +} |