Browse Source

Copy unsafely

vvmk 6 years ago
parent
commit
7bcf2c9bf1

+ 1
- 1
README.md View File

@@ -1,4 +1,4 @@
1
-# TC-Concurrency
1
+-Concurrency
2 2
 
3 3
 ## Monkey Typewriter
4 4
 According to Wikipedia:

+ 6
- 2
src/main/java/io/zipcoder/Copier.java View File

@@ -9,13 +9,17 @@ import java.util.Iterator;
9 9
 public abstract class Copier implements Runnable {
10 10
     // We use an iterator so each monkey / thread can copy an individual word.
11 11
     public Iterator<String> stringIterator;
12
-    public String copied;
12
+    protected StringBuffer buffer; // You want unsafe? Try using StringBuilder instead.
13 13
 
14 14
     public Copier(String toCopy) {
15 15
         // Take the input string, split it on spaces, turn that array to an arraylist, and then grab its iterator.
16 16
         this.stringIterator = Arrays.asList(toCopy.split(" ")).iterator();
17
-        this.copied = "";
17
+        buffer = new StringBuffer();
18 18
     }
19 19
 
20 20
     public abstract void run();
21
+
22
+    public String getCopy() {
23
+        return buffer.toString();
24
+    }
21 25
 }

+ 9
- 2
src/main/java/io/zipcoder/MonkeyTypewriter.java View File

@@ -1,6 +1,8 @@
1 1
 package io.zipcoder;
2 2
 
3 3
 public class MonkeyTypewriter {
4
+    private static final int fMONKEYS = 5;
5
+
4 6
     public static void main(String[] args) {
5 7
         String introduction = "It was the best of times,\n" +
6 8
                 "it was the blurst of times,\n" +
@@ -23,16 +25,21 @@ public class MonkeyTypewriter {
23 25
         // Do all of the Monkey / Thread building here
24 26
         // For each Copier(one safe and one unsafe), create and start 5 monkeys copying the introduction to
25 27
         // A Tale Of Two Cities.
26
-
28
+        UnsafeCopier uc = new UnsafeCopier(introduction);
29
+        for (int i = 0; i < fMONKEYS; i++) {
30
+            Thread monkey = new Thread(uc);
31
+            monkey.start();
32
+        }
27 33
 
28 34
         // This wait is here because main is still a thread and we want the main method to print the finished copies
29 35
         // after enough time has passed.
30 36
         try {
31 37
             Thread.sleep(1000);
32
-        } catch(InterruptedException e) {
38
+        } catch (InterruptedException e) {
33 39
             System.out.println("MAIN INTERRUPTED");
34 40
         }
35 41
 
36 42
         // Print out the copied versions here.
43
+        System.out.println(uc.getCopy());
37 44
     }
38 45
 }

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

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