[英]Display difference between volatile and usual variable in Java
我試圖創建一個示例來顯示volatile和常規變量之間的區別,如:
package main;
public class TestVolatile extends Thread {
public int l = 5;
public volatile int m = -1;
public TestVolatile(String str) {
super(str);
}
public void run() {
int i = 0;
while ((l > 1) && (l < 10)) {
if (m >= 0) {
m++;
}
i++;
l = 5;
System.out.println("5=" + i + " m=" + m);
}
}
public static void main(String[] args) throws InterruptedException {
TestVolatile tva = new TestVolatile("ThreadA");
tva.start();
sleep(5);
synchronized (tva) {
tva.m = 5;
tva.l = 10;
}
}
}
所以m
是不穩定的, l
不是。 我想從while循環退出取決於l
的值。
因為l
的值不是易變的 - 在分配l
后, m
將至少增加1次。但是我已經運行了10次代碼並且總是m == 5。
所以我想我錯了。 如何解決這個問題? 謝謝。
謝謝你的回答,但並非一切順利。 我設置如下:
volatile int x = 0;
volatile int y = 0;
所以現在變量必須相同! 但事實並非如此。
x: 346946234 y: 346946250
x: 346946418 y: 346946422
x: 346946579 y: 346946582
x: 346946742 y: 346946745
x: 346946911 y: 346946912
您正在同步主線程和測試線程。 因此,Java保證使其他線程可以執行任何可見的更改。
順便說一句,不可能構建一個確定性地顯示易失性和非易失性之間差異的例子。 你可以期望的最好的方法是獲得一個以極高概率顯示差異的程序。 如果線程在同一個核心上交錯運行。 您將無法顯示任何差異。
以下程序在我的計算機上顯示易失性和非易失性變量之間的差異。
public class ShowVolatile {
final static int NUM_THREADS = 1;
int x = 0;
volatile int y = 0;
public static void main(String... args) {
final ShowVolatile sv = new ShowVolatile();
for (int i=0; i< NUM_THREADS; i++) {
new Thread(new Runnable() {
public void run() {
while (true) {
sv.x += 1;
sv.y += 1;
}
}
}).start();
}
while (true) {
System.out.println("x: " + sv.x + " y: " + sv.y);
}
}
}
如果增加線程數,您將看到其他同步未命中。 但是線程數為1就足夠了。 至少在我的硬件上是四核i7。
讓多個線程在volatile變量上執行並發非同步++
應該會有所幫助。 然而,它永遠不會是確定性的。 它可能還取決於底層操作系統和CPU。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.