我对以下代码有些担心。
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;
}
}
这是我的测试课-
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();
}
}
我需要的是,如果一个线程获取了文件,其他线程需要忽略该文件。对这里的线程过程不是很清楚,有些困惑。
- 我需要在
synchronize
块中进行重命名过程吗? - 我的
FileUtil
方法是线程安全的吗? - 由于
Task
类为每个线程创建一个新实例,因此每个线程都应该有自己的file
对象。因为在这种情况下对象是在堆中创建的,它会被共享吗?还是一个线程在堆中有自己的对象堆栈? - 如果两个线程同时尝试重命名文件会发生什么?(我需要制作我的 util 方法
synchronize
吗?)
非常感谢您帮助消除我的困惑。谢谢大家。