Skip to content

Instantly share code, notes, and snippets.

@beoliver
Created April 26, 2015 08:10
Show Gist options
  • Save beoliver/410b00290ee1eef18ddb to your computer and use it in GitHub Desktop.
Save beoliver/410b00290ee1eef18ddb to your computer and use it in GitHub Desktop.
java threading 'synchronized', each thread calls shared container once
public class Main {
public static void main(String[] args) {
String[] words = {"a", "b", "c", "a", "a", "c", "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) {}
}
System.out.println(sharedValue.getContents());
System.exit(0);
}
}
class Worker implements Runnable {
private int count = 0;
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() {
// System.out.println("new thread running");
for (; i <= j; i++) {
if (values[i].equals(key)) {
// System.out.println("match found at index " + i);
count++;
}
}
// System.out.println("thread has matched " + count + " items");
sharedValue.add(count);
}
}
class SharedValue {
private Integer number = 0;
public SharedValue() {}
public Integer getContents() {
return number;
}
public synchronized void add(Integer count) {
number += count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment