Ahmad Rusdi пре 6 година
родитељ
комит
77d75c691d

+ 23
- 1
src/main/java/io/zipcoder/MonkeyTypewriter.java Прегледај датотеку

@@ -18,12 +18,22 @@ public class MonkeyTypewriter {
18 18
                 "we were all going direct the other way--\n" +
19 19
                 "in short, the period was so far like the present period, that some of\n" +
20 20
                 "its noisiest authorities insisted on its being received, for good or for\n" +
21
-                "evil, in the superlative degree of comparison only.";
21
+                "evil, in the superlative degree of comparison only. ";
22 22
 
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 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
+        }
33
+
34
+        for (int i = 0; i < 5; i++) {
35
+            new Thread(safe).start();
36
+        }
27 37
 
28 38
         // This wait is here because main is still a thread and we want the main method to print the finished copies
29 39
         // after enough time has passed.
@@ -34,5 +44,17 @@ public class MonkeyTypewriter {
34 44
         }
35 45
 
36 46
         // Print out the copied versions here.
47
+        System.out.println(unsafe.copied);
48
+        if (unsafe.copied.equals(introduction)) {
49
+            System.out.println("UNSAFE PASS");
50
+        } else {
51
+            System.out.println("UNSAFE FAIL");
52
+        }
53
+        System.out.println(safe.copied);
54
+        if (safe.copied.equals(introduction)) {
55
+            System.out.println("SAFE PASS");
56
+        } else {
57
+            System.out.println("SAFE FAIL");
58
+        }
37 59
     }
38 60
 }

+ 11
- 1
src/main/java/io/zipcoder/SafeCopier.java Прегледај датотеку

@@ -4,5 +4,15 @@ 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
+    public SafeCopier(String text) {
10
+        super(text);
11
+    }
12
+
13
+    synchronized public void run() {
14
+        while (this.stringIterator.hasNext()) {
15
+            copied += stringIterator.next() + " ";
16
+        }
17
+    }
8 18
 }

+ 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 (this.stringIterator.hasNext()) {
14
+           copied += stringIterator.next() + " ";
15
+        }
13 16
     }
14 17
 }