Java多线程,捕获更新的布尔变量。

huangapple go评论67阅读模式
英文:

Java multithreading, capture updated boolean variables

问题

我想要做类似这样的事情

while (true) {
    if (my_boolean) {  // my_boolean被其他线程更新
        做一些事情;
        退出循环;
    }
    做另一些事情;
} 

我的问题是,my_boolean会被另一个线程中的另一个方法更新。有时可以捕获到这样的更新,有时则无法。是否有一种一致的方法来解决这个问题?

英文:

I want to do something like this

while (true) {
    if (my_boolean) {  //my_boolean is being updated by other threads
        do something;
        break;
    }
    do something else;
} 

my problem is, my_boolean is being updated by another method in another thread. Sometimes such updates can be captured, sometimes not. Is there any consistent way to work around this?

答案1

得分: 1

你可以将那个布尔值声明为 volatile

英文:

You can declare that boolean as volatile.

huangapple
  • 本文由 发表于 2020年9月2日 23:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63708766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定