线程互斥(互斥变量)

下面代码模拟一个场景:

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;
  }
}

转载于:https://www.cnblogs.com/cz305679760/p/5111988.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值