1
回答
java 并发写文件问题
滴滴云服务器,限时包月0.9元,为开发者而生>>>   

private BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);

@Autowired
private PhoneFileUploadMD5Dao phoneFileUploadMD5Dao;


@Override
public ResponseBo savePhoneFileInfo(String fileInfoJson) {
ResponseBo responseBo = new ResponseBo();
if(!StringUtils.isBlank(fileInfoJson)){
try {
queue.put(fileInfoJson);
} catch (InterruptedException e) {
log.info("队列已满,等待",e);
}

List<String> keys = phoneFileUploadMD5Dao.getKeys();

PhoneBo phoneBo = JsonUtil.toObect(fileInfoJson, PhoneBo.class);
List<PhoneBo.PhoneFile> a = phoneBo.getList();
for(PhoneBo.PhoneFile tmp : a){
PhoneFileUploadMd5 pMd5 = phoneFileUploadMD5Dao.getByMD5(tmp.getMD5());
if(keys.contains(tmp.getMD5())){
if(pMd5.getNetwork() == 1 || pMd5.getNetwork() == phoneBo.getPhoneInfo().getNetwork()){
responseBo.addData("md", tmp.getMD5());//需要上传文件的MD5值
break;
}
}
}
}else{
new ServiceException(ServiceReturnCode.FAILD, "参数错误,信息不能为空!");
}

return responseBo;
}

public void init(){
log.info("开始线程");
new Thread(new Runnable() {


public void run() {
worker();
}


}).start();
}

public void worker(){
while (true) {
try {
String event = this.take();
if (!StringUtils.isBlank(event)) {
handle(event);
}
} catch (Throwable t) {
log.error(t.getMessage());
try {
Thread.sleep(1000 * 5);//等待5秒
} catch (InterruptedException ie) {
log.debug(ie);
}
}
}
}

private String take() {
try {
return this.queue.take();
} catch (InterruptedException ie) {
log.info("phone fileinfo input fail");
return "";
}
}

private void handle(String event){
FileUtils.wireFile(event);
}



这段代码会出现同时写同一个文件的BUG吗?如果会出现,怎么改好点,求大神

举报
顶部