JAVA多线程并发操作全局变量
现在我有一个需求:
?就是我从数据库获取一个值,但是返回给用户的过程中,后台的很多线程还是在操作这个变量,就是因为这个时间差,导致用户获取的值
?
package com.message.application; import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable; public class ApplicationValue { private static Hashtable licenceKeyHashTable; static { System.out.println("ApplicationValue static代码块"); licenceKeyHashTable = new Hashtable(); licenceKeyHashTable.put("A", 1000000); } public static long getLicenKeyValue() { long value = Long.parseLong(licenceKeyHashTable.get("A").toString()); return value; } public static void setLicenKeyValue(long val) { licenceKeyHashTable.put("A", val); } }?
package com.message.quartz.schedule; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.message.application.ApplicationValue; import com.message.application.MessageContext; import com.message.services.interfaces.IMessageSV; public class MessageSchedule { private static Log log = LogFactory.getLog(MessageSchedule.class); public void send() throws Exception { log.info("=========================START========================="); //log.info(arg0); long currentVal = ApplicationValue.getLicenKeyValue(); log.info("当前线程名称:"+Thread.currentThread().getName()+":"+currentVal); if(getModNum() == 1) { log.info("名称为1的线程sleep3秒"); Thread.currentThread().sleep(3000); } ApplicationValue.setLicenKeyValue(--currentVal); log.info("=========================END========================="); } public void send2() throws Exception { log.info("=========================START========================="); int modNum = getModNum(); IMessageSV sv = (IMessageSV) MessageContext.getBean("IMessageSV"); sv.dealMessages(modNum); log.info("=========================END========================="); } public static int getModNum() { String tName = Thread.currentThread().getName(); String modNum = tName.substring(tName.length() - 1, tName.length()); log.info(tName + "-----modNum:" + modNum); return Integer.parseInt(modNum); } }?
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。