Sharing a variable between multiple different threads

前端 未结 6 1900
长发绾君心
长发绾君心 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:07

    In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

    public class Test {
      class Control {
        public volatile boolean flag = false;
      }
      final Control control = new Control();
    
      class T1 implements Runnable {
        @Override
        public void run() {
          while ( !control.flag ) {
    
          }
        }
      }
    
      class T2 implements Runnable {
        @Override
        public void run() {
          while ( !control.flag ) {
    
          }
        }
      }
    
      private void test() {
        T1 main = new T1();
        T2 help = new T2();
    
        new Thread(main).start();
        new Thread(help).start();
      }
    
      public static void main(String[] args) throws InterruptedException {
        try {
          Test test = new Test();
          test.test();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    

提交回复
热议问题