瀏覽代碼

Merge 10feef9f04d46b5d02cc95e404adf7b60f64de9a into dbc7033eb3d6c33c19985384bea0b1a977cc30d3

erc91087 6 年之前
父節點
當前提交
aab79ab54e
沒有帳戶連結到提交者的電子郵件
共有 2 個文件被更改,包括 34 次插入1 次删除
  1. 12
    1
      src/main/java/io/zipcoder/SafeCopier.java
  2. 22
    0
      src/main/java/io/zipcoder/UnsafeCopier.java

+ 12
- 1
src/main/java/io/zipcoder/SafeCopier.java 查看文件

@@ -4,5 +4,16 @@ package io.zipcoder;
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 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 查看文件

@@ -10,5 +10,27 @@ public class UnsafeCopier extends Copier {
10 10
     }
11 11
 
12 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
+ */