Skip to content

Instantly share code, notes, and snippets.

@LeoAndo
Last active June 5, 2024 22:09
Show Gist options
  • Save LeoAndo/60aefc39403472c2f9658cf15dbe4b73 to your computer and use it in GitHub Desktop.
Save LeoAndo/60aefc39403472c2f9658cf15dbe4b73 to your computer and use it in GitHub Desktop.
フィールドの修飾子volatileのサンプル
public class VolatileSample {
private static volatile int count = 0; // メインメモリの変数に対して読み書きする
// private static int count = 0; // 各スレッドの対応するキャッシュした変数に対して読み書きする
public static void main(String[] args) {
new MultiThread1().start();
new MultiThread2().start();
}
// Thread-0
private static class MultiThread1 extends Thread {
public void run() {
while (count < 3) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s: before count = %d\n", getName(), count);
count++; // カウントアップする.
System.out.printf("%s: after count = %d\n", getName(), count);
}
System.out.println("MultiThread1(Thread-0) finish");
}
}
// Thread-1
private static class MultiThread2 extends Thread {
public void run() {
int beforeCount = count; // 元の値を退避する.
while (count < 3) {
if (beforeCount != count) { // カウンター変数に更新があったら、標準出力する.
System.out.printf("%s: before count = %d, after count = %d\n", getName(), beforeCount, count);
beforeCount = count;
}
}
System.out.println("MultiThread2(Thread-1) finish");
}
}
}
@LeoAndo
Copy link
Author

LeoAndo commented Jun 3, 2024

スクリーンショット 2024-06-04 6 53 08

@LeoAndo
Copy link
Author

LeoAndo commented Jun 3, 2024

スクリーンショット 2024-06-04 6 53 25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment