alizalang 6 年之前
父節點
當前提交
3797780a4a

+ 2
- 0
src/main/java/io/zipcoder/Copier.java 查看文件

@@ -18,4 +18,6 @@ public abstract class Copier implements Runnable {
18 18
     }
19 19
 
20 20
     public abstract void run();
21
+
22
+
21 23
 }

+ 12
- 0
src/main/java/io/zipcoder/MonkeyTypewriter.java 查看文件

@@ -24,15 +24,27 @@ public class MonkeyTypewriter {
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 26
 
27
+        UnsafeCopier unsafe = new UnsafeCopier(introduction);
28
+        SafeCopier safe = new SafeCopier(introduction);
29
+
30
+        for (int i = 0; i < 5; i++){
31
+            new Thread(unsafe).start();
32
+            new Thread(safe).start();
33
+        }
34
+
27 35
 
28 36
         // This wait is here because main is still a thread and we want the main method to print the finished copies
29 37
         // after enough time has passed.
30 38
         try {
31 39
             Thread.sleep(1000);
40
+
32 41
         } catch(InterruptedException e) {
33 42
             System.out.println("MAIN INTERRUPTED");
34 43
         }
35 44
 
36 45
         // Print out the copied versions here.
46
+        System.out.println("UNSAFE COPIER:\n"+unsafe.copied);
47
+        System.out.println();
48
+        System.out.println("SAFE COPIER:\n"+safe.copied);
37 49
     }
38 50
 }

+ 31
- 2
src/main/java/io/zipcoder/SafeCopier.java 查看文件

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

+ 3
- 0
src/main/java/io/zipcoder/UnsafeCopier.java 查看文件

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