Garrett Arant пре 6 година
родитељ
комит
a8c990ab79

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

@@ -1,5 +1,7 @@
1 1
 package io.zipcoder;
2 2
 
3
+import java.util.ArrayList;
4
+
3 5
 public class MonkeyTypewriter {
4 6
     public static void main(String[] args) {
5 7
         String introduction = "It was the best of times,\n" +
@@ -38,6 +40,8 @@ public class MonkeyTypewriter {
38 40
         monkey5.start();
39 41
 
40 42
         SafeCopier safeCopier = new SafeCopier(introduction);
43
+
44
+        ArrayList<Thread>monkeys = new ArrayList<Thread>();
41 45
         Thread monkeySafe1 = new Thread(safeCopier);
42 46
         Thread monkeySafe2 = new Thread(safeCopier);
43 47
         Thread monkeySafe3 = new Thread(safeCopier);
@@ -51,6 +55,7 @@ public class MonkeyTypewriter {
51 55
         monkeySafe5.start();
52 56
 
53 57
 
58
+
54 59
         // This wait is here because main is still a thread and we want the main method to print the finished copies
55 60
         // after enough time has passed.
56 61
         try {
@@ -64,5 +69,6 @@ public class MonkeyTypewriter {
64 69
         System.out.println(unsafeCopier.copied);
65 70
         System.out.println("----------Safe----------");
66 71
         System.out.println(safeCopier.copied);
72
+
67 73
     }
68 74
 }

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

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