Last active
June 5, 2024 22:09
-
-
Save LeoAndo/60aefc39403472c2f9658cf15dbe4b73 to your computer and use it in GitHub Desktop.
フィールドの修飾子volatileのサンプル
This file contains 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
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"); | |
} | |
} | |
} |
Author
LeoAndo
commented
Jun 3, 2024
![スクリーンショット 2024-06-04 6 53 25](https://private-user-images.githubusercontent.com/16476224/336240926-cb331ac1-568b-4a41-947d-2f690ac7ec13.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjE5MjU2OTQsIm5iZiI6MTcyMTkyNTM5NCwicGF0aCI6Ii8xNjQ3NjIyNC8zMzYyNDA5MjYtY2IzMzFhYzEtNTY4Yi00YTQxLTk0N2QtMmY2OTBhYzdlYzEzLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA3MjUlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNzI1VDE2MzYzNFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTllMGZmNWY3YmFmZDM4ZTQ3ZmMwYzgwMjVkMjlmYWFkOTlkZDdjZDJiM2U3ZDE3YWY3MGFhOWYyMjVkZTI1ZGEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.kvVqtSPZGh12k4H3nMT9JIPtpDqM92b7YT0CAxWz1uQ)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment