Skip to content

Instantly share code, notes, and snippets.

@takai
Created February 14, 2011 12:49
Show Gist options
  • Save takai/825824 to your computer and use it in GitHub Desktop.
Save takai/825824 to your computer and use it in GitHub Desktop.
package app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class UnsafeCounter {
private int nextValue = 0;
public int getNextValue() {
return nextValue++;
}
public static void main(String[] args) throws Exception {
final List<Integer> results = Collections.synchronizedList(new ArrayList<Integer>());
final UnsafeCounter c = new UnsafeCounter();
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i < 3000; i++) {
results.add(c.getNextValue());
}
}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
t1.join();
t2.join();
int total = 0;
for (int i : results) {
total += i;
}
System.out.println(total);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment