老师,关于可见性的问题
来源:9-1 synchronized

张婧仪
2025-01-23
老师,在我没有使用Volatile和Synchronized关键字时,为啥加了睡眠就有可见性,不加就没有可见性呢?
代码如下:
public class ThreadSafeCache {
int result = 100;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public static void main(String[] args) throws InterruptedException {
ThreadSafeCache threadSafeCache = new ThreadSafeCache();
Visibility visibility = new Visibility(threadSafeCache);
for (int i = 0; i < 8; i++) {
Thread thread = new Thread(visibility);
thread.start();
}
Thread.sleep(1000);
threadSafeCache.setResult(200);
int x = 1;
while (true) {
x++;
}
}
}
class Visibility implements Runnable {
private ThreadSafeCache threadSafeCache;
public Visibility(ThreadSafeCache threadSafeCache) {
this.threadSafeCache = threadSafeCache;
}
@Override
public void run() {
int x = 0;
while (threadSafeCache.getResult() == 100) {
x++;
/**
* 加了睡眠就有可见性,不加就没有
*/
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(x);
}
}
写回答
1回答
-
翔仔
2025-01-26
同学好,这块看了下 sleep会让出cpu执行权,这块主线程有机会执行后,就能拿到值了
022025-01-28
相似问题