gpt4 book ai didi

java - 文件重命名时的线程安全

转载 作者:行者123 更新时间:2023-12-01 15:16:06 25 4
gpt4 key购买 nike

我对以下代码有一些疑问。

public class Task implements Runnable {

String filePath = "C:\\Backup\\test.xml";

@Override
public void run() {

File file = new File(filePath);

try {

System.out.println(Thread.currentThread() + " Renaming " + FileUtil.changeFileExtention(file));
Thread.sleep(20000);
System.out.println(Thread.currentThread() + " Renaming Back " + FileUtil.changeFileExtention(file));

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

这里的“FileUtil”是一个类。

public class FileUtil {

public static File changeFileExtention(File file) throws Exception {

File newFile = null;

int extIndex = file.getName().lastIndexOf(".");

String ext = getExtentionFromFile(file);

System.out.println("File Extention is [" + ext + "] for file [" + file.getName() + "].");

if (ext.equalsIgnoreCase(".xml")) {

newFile = buildChangedFile(file, extIndex, ".txt");

} else if (ext.equalsIgnoreCase(".proc")) {

newFile = buildChangedFile(file, extIndex, ".xml");
}

file.renameTo(newFile);

return newFile;

}

public static String getExtentionFromFile(File file) throws Exception {

String fileName = file.getName();

int extIndex = fileName.lastIndexOf(".");

if (extIndex != -1) {

return fileName.substring(extIndex);

} else {

String msg = "File extention not found for file [" + fileName + "]";
System.out.println(msg);
throw new Exception(msg);
}
}

private static File buildChangedFile(File file, int extIndex, String targetExtention) throws Exception {

String fileName = file.getName();

File renamedFile = null;

if (file.exists()) {

String newFileName = fileName.substring(0, extIndex) + targetExtention;

System.out.println("New File name -" + newFileName);

String fullPathWithName = file.getParent() + "/" + newFileName;

renamedFile = new File(fullPathWithName);

} else {

String msg = "File not exisit in location [" + file.getAbsolutePath() + "]";
System.out.println(msg);
throw new Exception(msg);
}

return renamedFile;
}

}

这是我的测试类(class) -

public class Test {


public static void main(String[] args) {

Thread thread1 = new Thread(new Task());
Thread thread2 = new Thread(new Task());
Thread thread3 = new Thread(new Task());

thread1.start();
thread2.start();
thread3.start();
}

}

我需要的是,如果一个线程获取了该文件,其他线程需要忽略该文件。对这里的线程流程不太清楚,有些困惑。

  1. 我需要在 synchronize block 中进行重命名过程吗?
  2. 我的 FileUtil 方法是线程安全的吗?
  3. 由于Task类为每个线程创建一个新实例,因此每个线程都应该有自己的file对象。由于对象是在堆中创建的,在这种情况下它会被共享吗?或者一个线程在堆中是否有自己的对象堆栈?
  4. 如果两个线程尝试同时重命名文件会发生什么? (我是否需要使我的 util 方法同步?)

非常感谢您帮助消除我的困惑。提前谢谢大家。

最佳答案

显然,如果您有一个文件要更改名称,则不需要多个线程。否则,这看起来像是典型的消费者-生产者问题。作为替代解决方案,您可以使用阻塞队列结构来使用线程安全性。一个(或多个)线程将文件名添加到队列中,并且所有使用者线程都采用文件名来更改其名称。

您可以查看LinkedBlockingQueue

关于java - 文件重命名时的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com