Skip to content

Instantly share code, notes, and snippets.

@kazuki-ma
Created May 16, 2012 11:27
Show Gist options
  • Save kazuki-ma/2709655 to your computer and use it in GitHub Desktop.
Save kazuki-ma/2709655 to your computer and use it in GitHub Desktop.
Long をロックする注意
public class TestSynchronized {
public static void main(String[] args) {
Runnable action = new Runnable() {
Long var = new Long(0); // Long 方 var
public void run() {
for (long i = 0; i < 10_000_000L; ++i) { // 1000万回ループ内で
synchronized (var) { // ロックして
var++; // インクリメント!
}
}
}
public String toString() {
return String.valueOf(var); // 値を表示するようにする
}
};
Thread t1 = new Thread(action); // 二つスレッドを立ち上げて
Thread t2 = new Thread(action);
t1.start(); // 開始!
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(action);
// join して表示すると?
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment