Created
February 14, 2011 12:49
-
-
Save takai/825824 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 characters
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