我正在尝试用5个不同的线程编辑一个json文件,然后将它复制5次到相同的目标路径。如您所见,存在并发问题。
对于copy方法,我尝试了以下方法:
public static void copyFile(String originPath, String destinationPath, String file) throws IOException {
logger.debug("Starting copyFile of" + file);
FileChannel channel = null;
File lockFile = new File(originPath + file);
try {
logger.debug("Comienza el proceso de procesado del json del fichero:" + file);
channel = extracted(lockFile).getChannel();
FileLock fileLock = null;
try {
fileLock = channel.lock();
} catch(OverlappingFileLockException e) {
logger.error("3 "+e.getMessage());
Thread.sleep(200);
}
FileUtils.copyFile(FileUtils.getFile(originPath + file), FileUtils.getFile(destinationPath + file));
logger.debug("The copy of " + file + " ends.");
fileLock.release();
channel.close();
} catch (IOException e) {
logger.error("Failing to copy "+file " to " + destinationPath + e.getMessage());
}
}我得到的是null和IOException,我想要的就是当一个文件被处理时,其他线程一个接一个地在队列中等待它。
发布于 2019-10-06 15:36:02
如果我理解正确的话,你的问题是当你的一个线程试图复制一个文件时,其他线程在队列中等待,然后一个接一个地开始他们的工作。
您可以通过以下代码来实现这一点
public class FileLock {
static Semaphore semaphore = new Semaphore(1);
public static void copyFile(String originPath, String destinationPath, String file) throws IOException {
try {
semaphore.acquire();
logger.debug("Comienza el proceso de procesado del json del fichero:" + file);
FileUtils.copyFile(FileUtils.getFile(originPath + file), FileUtils.getFile(destinationPath + file));
logger.debug("The copy of " + file + " ends.");
} catch (IOException | InterruptedException e) {
logger.error("Failing to copy " + file" to " + destinationPath + e.getMessage());
} finally {
semaphore.release();
}
}
}https://stackoverflow.com/questions/58253025
复制相似问题