소스 검색

first attempt

Eric Foster 6 년 전
부모
커밋
2a0ea95f85
3개의 변경된 파일38개의 추가작업 그리고 1개의 파일을 삭제
  1. 10
    0
      src/main/java/io/zipcoder/MonkeyTypewriter.java
  2. 23
    1
      src/main/java/io/zipcoder/SafeCopier.java
  3. 5
    0
      src/main/java/io/zipcoder/UnsafeCopier.java

+ 10
- 0
src/main/java/io/zipcoder/MonkeyTypewriter.java 파일 보기

@@ -23,7 +23,15 @@ public class MonkeyTypewriter {
23 23
         // Do all of the Monkey / Thread building here
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
+        UnsafeCopier unsafe = new UnsafeCopier(introduction);
27
+        for (int i=5; i>0; i--) {
28
+            new Thread(unsafe).start();
29
+        }
26 30
 
31
+        SafeCopier safe = new SafeCopier(introduction);
32
+        for (int i=5; i>0; i--) {
33
+            new Thread(safe).start();
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.
@@ -34,5 +42,7 @@ public class MonkeyTypewriter {
34 42
         }
35 43
 
36 44
         // Print out the copied versions here.
45
+        System.out.println("Unsafe version: \n" + unsafe.copied);
46
+        System.out.println("Safe version: \n" + safe.copied);
37 47
     }
38 48
 }

+ 23
- 1
src/main/java/io/zipcoder/SafeCopier.java 파일 보기

@@ -1,8 +1,30 @@
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 {
10
+public class SafeCopier extends Copier {
11
+
12
+    public SafeCopier(String toCopy) {
13
+        super(toCopy);
14
+    }
15
+
16
+    public void run() {
17
+        ReadWriteLock lock = new ReentrantReadWriteLock();
18
+        lock.writeLock().lock();
19
+        lock.readLock().lock();
20
+        try {
21
+            while (stringIterator.hasNext()){
22
+                copied += stringIterator.next() + " ";
23
+            }
24
+        } finally {
25
+            lock.writeLock().unlock();
26
+            lock.readLock().unlock();
27
+        }
28
+
29
+    }
8 30
 }

+ 5
- 0
src/main/java/io/zipcoder/UnsafeCopier.java 파일 보기

@@ -10,5 +10,10 @@ 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
     }
17
+
18
+
14 19
 }