Eric Cordell 6 anni fa
parent
commit
10feef9f04

+ 12
- 1
src/main/java/io/zipcoder/SafeCopier.java Vedi File

4
  * Make this extend the Copier like `UnsafeCopier`, except use locks to make sure that the actual intro gets printed
4
  * 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.
5
  * correctly every time.  Make the run method thread safe.
6
  */
6
  */
7
-public class SafeCopier {
7
+public class SafeCopier extends Copier{
8
+
9
+    // constructor
10
+    public SafeCopier(String toCopy) {
11
+        super(toCopy);
12
+    }
13
+
14
+    public synchronized void run() {
15
+        while ( stringIterator.hasNext()) {
16
+            copied += stringIterator.next() + " ";
17
+        }
18
+    }
8
 }
19
 }

+ 22
- 0
src/main/java/io/zipcoder/UnsafeCopier.java Vedi File

10
     }
10
     }
11
 
11
 
12
     public void run() {
12
     public void run() {
13
+        while ( stringIterator.hasNext()) {         // stringIterator comes from Copier
14
+            copied += stringIterator.next() + " ";
15
+        }
13
     }
16
     }
14
 }
17
 }
18
+
19
+
20
+/*
21
+Part 1
22
+
23
+Made for you is an abstract base class of Copier which has a constructor that takes a String and turns that into an iterator.
24
+This will allow us to traverse the text to be copied and pass it along to each monkey (thread).
25
+
26
+Extend Copier in UnsafeCopier.
27
+Then, write a run method that will have the monkey grab the next word and append it to the copy.
28
+
29
+Modify MonkeyTypewriter to create 5 monkeys (threads) using the UnsafeCopier and start them.
30
+
31
+After the sleep, print out the results of the unsafely copied passage.
32
+
33
+Part 2
34
+
35
+Finish the SafeCopier and then call that from the main method, in addition to the unsafe version.
36
+ */