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

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

  • 先启动线程,标识是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> 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 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();//一定要唤醒其他线程操作,否则就容易死锁了
		}

 

 

 

你可能感兴趣的:(J2EE核心框架生态)