Skip to content

Instantly share code, notes, and snippets.

@beoliver
Created April 25, 2015 23:45
Show Gist options
  • Save beoliver/81cf7d62ac88270aba42 to your computer and use it in GitHub Desktop.
Save beoliver/81cf7d62ac88270aba42 to your computer and use it in GitHub Desktop.
simple example of using 'synchronized'
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++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment