我的应用程序有时应该读取和写入文件。而且这项工作可能发生在多线程中,所以我应该同步这些资源。这是我的代码:
// write to file
FileOutputStream fos = openFileOutput("data.dat", Context.MODE_PRIVATE);
synchronized (fos) {
ObjectOutputStream writer = new ObjectOutputStream(fos);
// continue to write
}
// read to file
FileInputStream fis = openFileInput("data.dat");
synchronized (fis) {
ObjectInputStream reader = new ObjectInputStream(fis);
// continue to read
}
上面的代码安全吗?这意味着“data.dat”总是只能在一个线程中读取或写入?如有错误,请指正。
谢谢:)
最佳答案
使用文件锁定:http://en.wikipedia.org/wiki/File_locking告诉其他线程输出文件正在使用中。如果输出文件由您的应用独占使用,则 synchronized
应防止其他线程同时执行该部分代码。或者,最后,您可以考虑使用IntentService
将请求排队并逐一处理
关于java - 安卓 : How to synchronized resource in right way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628905/