多线程的数据发送和同步锁的案例实战

多线程的数据发送的代码,说明线程同步的

  • 先启动线程,标识是threadKey = appType + "_" + datatype + "_" + sendWay,如果已经有这个线程,就不再启动新的线程。
		for (String sendWay : sendWayArray) {
			// 1.定义线程的唯一性
			String threadKey = appType + "_" + datatype + "_" + sendWay;
			if (threadMap.containsKey(threadKey)) {
				CommonThread thread = threadMap.get(threadKey);
				if (thread.isAlive()) {
					continue;
				}
			}
			CommonThread thread = new CommonThread(sendWay,
					ThreadStateFlag.getInstance(threadKey), datatype, sendFlag,
					appType, sendPath);
			thread.setName(threadKey);
			thread.start();
			threadMap.put(threadKey, thread);
		}
  • 下面是CommonThread 的run方法实现,设置同步锁threadStateFlag是一个单例对象,解决并发情况下的死锁问题:
	public void run() {
		synchronized (threadStateFlag) {
			List<HashMap<String, String>> unSendList = null;
			JSONObject data = null;
			String tableName = "sports";
			String querySql = String.format(baseQuerySql, tableName, sendFlag, "%" + appType + "%");
			unSendList = C3P0Util.getData(querySql);
			System.out.println("*******************print unSendList***********************");
			System.out.println(unSendList);
			if (unSendList.size() > 0) {
				for (HashMap<String, String> map : unSendList) {
					data = new JSONObject();
					data.put("appType", appType);
					data.put("dataType", map.get("dataType"));
					data.put("collectDate", map.get("receiveTime"));
					data.put("phone", map.get("phone"));
					data.put("dataValue", map.get("dataValue"));
					data.put("deviceID", map.get("deviceID"));
					data.put("company", map.get("company"));
					data.put("pname", map.get("pname"));
					data.put("teamName", map.get("teamName"));

					if (StrategyContext.sendData(data.toString(), sendPath, appType, sendWay)) {
						String updateSql = String.format(baseUpdateSql, tableName, sendFlag, map.get("id"));
						boolean updateSuccess = C3P0Util.executeUpdate(updateSql);
						System.out.println(updateSql);
						if(!updateSuccess){
							Log.error("send data success,update data fail,sql is "+updateSql);
						}
					}
				}
			}
			threadStateFlag.notify();//一定要唤醒其他线程操作,否则就容易死锁了
		}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值