Keith Brinker vor 6 Jahren
Ursprung
Commit
747e3ad9c5

+ 2
- 1
src/main/java/io/zipcoder/MonkeyTypewriter.java Datei anzeigen

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

+ 11
- 1
src/main/java/io/zipcoder/SafeCopier.java Datei anzeigen

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