Sharing a variable between multiple different threads

前端 未结 6 1902
长发绾君心
长发绾君心 2020-12-01 12:33

I want to share a variable between multiple threads like this:

boolean flag = true;
T1 main = new T1();
T2 help = new T2();
main.start();
help.start();
         


        
6条回答
  •  天涯浪人
    2020-12-01 13:08

    To make it visible between the instances of T1 and T2 you could make the two classes contain a reference to an object that contains the variable.

    If the variable is to be modified when the threads are running, you need to consider synchronization. The best approach depends on your exact requirements, but the main options are as follows:

    • make the variable volatile;
    • turn it into an AtomicBoolean;
    • use full-blown synchronization around code that uses it.

提交回复
热议问题