我的密码
synchronized (countInfo) {
count++;
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(countInfo));
writer.write(String.valueOf(count));
writer.close();
}这里,countInfo引用了一个文件和编写这段代码的方法--我的多个线程。我在“同步(countInfo)”行中得到一个空指针异常。我知道这是因为在这一行还不知道countInfo被初始化为,因此为此,我将不得不移动
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");同步块外部的行。但是如果我这样做,那么所有访问我的方法的线程都会缓存一个新文件。但我的目标只是其中一个线程(这个方法中的第一个线程)必须创建一个文件,所有其他线程都应该只读取创建文件中的信息。我怎样才能做到这一点?请帮帮忙。我对java和多线程很陌生!请丰富我的知识!!提前谢谢!
UPDATE -解释流程的图像。

标记为黄色、跨会话文件访问的行将永远不会发生,因为我使用了附加到文件名的会话ID。
发布于 2014-03-25 11:51:42
如果你读到一些关于线程安全单字或双通道锁定机制的文章,它会对你有所帮助。对于您的场景,您可以这样做(可能是为了清晰的代码,分离用于文件创建和数据写入的逻辑):
//make countinfo volatile
public volatile File countInfo = null;
.
.
public void writeIntoFile(){
countInfo = getFile();
synchronized (countInfo) {
count++;
BufferedWriter writer = new BufferedWriter(new FileWriter(countInfo));
writer.write(String.valueOf(count));
writer.close();
}
}
public File getFile(){
if(countInfo==null){
synchronized (this){
if(countInfo==null){
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");
}
}
}
return countInfo;
}https://stackoverflow.com/questions/22589315
复制相似问题