zoukankan      html  css  js  c++  java
  • 线程互斥(互斥变量)

    下面代码模拟一个场景:

    A使用线程调用B来处理东西,但是B处理的时候需要一个Map,map内容需要从数据库查

    而这个map会因其他模块修改数据库不断的变化。

    为了保证处理的正确性,需要线程定时更新map,

    更新map时需要A停止线程,等B更新好map再开始。

    下面代码map并未出现,

    replace()方法代表更新map

    handle()代码处理

    B中ready作为互斥变量

    import java.util.Timer;

    import java.util.TimerTask;

    /**
    * 线程互斥
    * @author zhuo
    *
    */
    public class MutualExclusionVariable {
      public static void main(String[] args) {
        A a = new A();
        Timer timer1 = new Timer();
        timer1.schedule(a.task, 0, 100);
        Timer timer2 = new Timer();
        timer2.schedule(a.b.task, 0, 10000);
      }

    }

    class A{
      B b = new B();
      int i = 1;
      TimerTask task = new TimerTask() {
        @Override
        public void run() {
          sendMessage();
        }
      };
      public void sendMessage() {
        synchronized (b.isReady()) {
          b.handle(String.valueOf(i++));
        }
      }
    }

    class B {
      String ready = "";
      TimerTask task = new TimerTask() {
        @Override
        public void run() {
          try {
            replace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      };

      public void handle(String str) {
        System.out.println(str);
      }

      public void replace() throws InterruptedException {
        synchronized (ready) {
          System.out.println("替换中.....");
          for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 100000; j++) {
              for (int k = 0; k < 1000000; k++) {

              }
            }
          }
          System.out.println("替换完成");
        }
      }

      public String isReady(){
        return ready;
      }
    }

  • 相关阅读:
    xmlTextTextReaderNodeType来读取XML元素的类型
    [转]关于两个坐标点的距离的计算问题
    Incorrect decrement of the reference count of an object that is not owned at this point by the caller1
    让ipad时时显示内存剩余量
    【转】苹果开发者账号注册流程
    自定义百度地图气泡
    [转] iOS 常用数学函数
    [转]JDK环境变量的配置
    纬度在换算距离上一度等于多少公里?
    [转]UIDevice uniqueGlobalDeviceIdentifier(百度地图API的那些事)
  • 原文地址:https://www.cnblogs.com/cz305679760/p/5111988.html
Copyright © 2011-2022 走看看