Created
April 25, 2015 23:45
Revisions
-
beoliver created this gist
Apr 25, 2015 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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++; } }