#17 it was the BLERST of labs -shivam

Open
shiv-365 wants to merge 1 commits from shiv-365/ZCW-MonkeysTypewritersOhMy:master into master

+ 35
- 0
src/main/java/io/zipcoder/MonkeyTypewriter.java View File

@@ -27,12 +27,47 @@ public class MonkeyTypewriter {
27 27
 
28 28
         // This wait is here because main is still a thread and we want the main method to print the finished copies
29 29
         // after enough time has passed.
30
+
31
+
32
+        UnsafeCopier u = new UnsafeCopier(introduction);
33
+        Thread monk1 = new Thread(u);
34
+        Thread monk2 = new Thread(u);
35
+        Thread monk3 = new Thread(u);
36
+        Thread monk4 = new Thread(u);
37
+        Thread monk5 = new Thread(u);
38
+        monk1.start();
39
+        monk2.start();
40
+        monk3.start();
41
+        monk4.start();
42
+        monk5.start();
43
+
44
+
45
+
46
+        SafeCopier s = new SafeCopier(introduction);
47
+        Thread monk6 = new Thread(s);
48
+        Thread monk7 = new Thread(s);
49
+        Thread monk8 = new Thread(s);
50
+        Thread monk9 = new Thread(s);
51
+        Thread monk0 = new Thread(s);
52
+        monk6.start();
53
+        monk7.start();
54
+        monk8.start();
55
+        monk9.start();
56
+        monk0.start();
57
+
58
+
59
+
30 60
         try {
31 61
             Thread.sleep(1000);
32 62
         } catch(InterruptedException e) {
33 63
             System.out.println("MAIN INTERRUPTED");
34 64
         }
35 65
 
66
+
67
+
36 68
         // Print out the copied versions here.
69
+        System.out.println(u.copied);
70
+        System.out.println("===================\n" + "===================");
71
+        System.out.println(s.copied);
37 72
     }
38 73
 }

+ 19
- 1
src/main/java/io/zipcoder/SafeCopier.java View File

@@ -1,8 +1,26 @@
1 1
 package io.zipcoder;
2 2
 
3
+import java.util.concurrent.locks.Lock;
4
+import java.util.concurrent.locks.ReentrantLock;
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
+    Lock lock = new ReentrantLock();
12
+
13
+    public SafeCopier(String toCopy) {
14
+        super(toCopy);
15
+    }
16
+
17
+    public void run() {
18
+        while(stringIterator.hasNext()){
19
+            lock.lock();
20
+            System.out.println(Thread.currentThread().getName());
21
+            copied += stringIterator.next();
22
+            lock.unlock();
23
+        }
24
+
25
+    }
8 26
 }

+ 5
- 0
src/main/java/io/zipcoder/UnsafeCopier.java View File

@@ -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
+        }
16
+
17
+
13 18
     }
14 19
 }