Aleena Rose-Mathew 6 vuotta sitten
vanhempi
commit
fddaabcf45

+ 20
- 0
src/main/java/io/zipcoder/MonkeyTypewriter.java Näytä tiedosto

@@ -23,12 +23,32 @@ public class MonkeyTypewriter {
23 23
         // Do all of the Monkey / Thread building here
24 24
         // For each Copier(one safe and one unsafe), create and start 5 monkeys copying the introduction to
25 25
         // A Tale Of Two Cities.
26
+        UnsafeCopier unsafeCopier=new UnsafeCopier(introduction);
27
+        for(int i=0;i<5;i++)
28
+        {
29
+
30
+            Thread thread=new Thread(unsafeCopier);
31
+            thread.start();
32
+
33
+        }
34
+
35
+        SafeCopier safeCopier=new SafeCopier(introduction);
36
+        for(int i=0;i<5;i++)
37
+        {
38
+
39
+            Thread thread=new Thread(safeCopier);
40
+            thread.start();
41
+
42
+        }
43
+
26 44
 
27 45
 
28 46
         // This wait is here because main is still a thread and we want the main method to print the finished copies
29 47
         // after enough time has passed.
30 48
         try {
31 49
             Thread.sleep(1000);
50
+            System.out.println("Unsafe"+unsafeCopier.copied);
51
+            System.out.println("Safe"+safeCopier.copied);
32 52
         } catch(InterruptedException e) {
33 53
             System.out.println("MAIN INTERRUPTED");
34 54
         }

+ 19
- 1
src/main/java/io/zipcoder/SafeCopier.java Näytä tiedosto

@@ -3,6 +3,24 @@ package io.zipcoder;
3 3
 /**
4 4
  * Make this extend the Copier like `UnsafeCopier`, except use locks to make sure that the actual intro gets printed
5 5
  * correctly every time.  Make the run method thread safe.
6
+ * https://www.journaldev.com/2377/java-lock-example-reentrantlock
6 7
  */
7
-public class SafeCopier {
8
+
9
+import java.util.*;
10
+import java.util.concurrent.locks.Lock;
11
+import java.util.concurrent.locks.ReentrantLock;
12
+
13
+public class SafeCopier  extends Copier{
14
+    public SafeCopier(String toCopy) {
15
+        super(toCopy);
16
+    }
17
+    private Lock lock=new ReentrantLock();
18
+    public void run() {
19
+        lock.lock();
20
+        while(stringIterator.hasNext())
21
+        {
22
+            copied=copied+stringIterator.next();
23
+        }
24
+        lock.unlock();
25
+    }
8 26
 }

+ 4
- 0
src/main/java/io/zipcoder/UnsafeCopier.java Näytä tiedosto

@@ -10,5 +10,9 @@ public class UnsafeCopier extends Copier {
10 10
     }
11 11
 
12 12
     public void run() {
13
+        while(stringIterator.hasNext())
14
+        {
15
+            copied=copied+stringIterator.next();
16
+        }
13 17
     }
14 18
 }