Keith Brinker пре 6 година
родитељ
комит
747e3ad9c5

+ 2
- 1
src/main/java/io/zipcoder/MonkeyTypewriter.java Прегледај датотеку

@@ -57,8 +57,9 @@ public class MonkeyTypewriter {
57 57
             System.out.println("MAIN INTERRUPTED");
58 58
         }
59 59
         // Print out the copied versions here.
60
+        System.out.println("UNSAFE\n");
60 61
         System.out.println(unsafeCopier.copied);
61
-
62
+        System.out.println("\nSAFE\n");
62 63
         System.out.println(safeCopier.copied);
63 64
     }
64 65
 }

+ 11
- 1
src/main/java/io/zipcoder/SafeCopier.java Прегледај датотеку

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