Skip to content

Instantly share code, notes, and snippets.

@beoliver
Created April 25, 2015 23:45

Revisions

  1. beoliver created this gist Apr 25, 2015.
    66 changes: 66 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@

    public class Main {

    public static void main(String[] args) {

    String[] words = {"a", "b", "c", "a", "a", "r", "b", "c", "a"};

    SharedValue sharedValue = new SharedValue();

    for (int i = 0; i <= 6; i += 3) {
    Thread t = new Thread(new Worker(words,i,i+2,"a",sharedValue));
    t.start();
    try { t.join(); } catch (InterruptedException e) {}
    // we use t.join() to make sure that all threads complete before
    // printing the result
    }
    System.out.println(sharedValue.getContents());
    System.exit(0);
    }
    }



    class Worker implements Runnable {

    private int i;
    private int j;
    private String[] values;
    private String key;
    private SharedValue sharedValue;

    public Worker(String[] values, int start, int stop, String key, SharedValue sharedValue) {
    this.i = start;
    this.j = stop;
    this.values = values;
    this.key = key;
    this.sharedValue = sharedValue;
    }

    @Override
    public void run() {
    for (; i <= j; i++) {
    if (values[i].equals(key)) {
    System.out.println("match found at index " + i);
    sharedValue.increment();
    }
    }
    }
    }


    class SharedValue {

    private Integer number = 0;

    public SharedValue() {}

    public Integer getContents() {
    return number;
    }

    public synchronized void increment() {
    number++;
    }

    }