以下方法不访问任何共享变量。它仍然不是线程安全的。我要么测试错了,要么我遗漏了一些东西。请解释。
方法:
public static boolean acquireFolderLock(File directoryPath) {
final String LOCK_FILE_NAME = ".lock";
boolean isLocked = false;
if(directoryPath != null && directoryPath.isDirectory()) {
File lockFile = new File(new StringBuilder(directoryPath.getAbsolutePath()).append(File.separatorChar).append(LOCK_FILE_NAME).toString());
if(lockFile.exists()) {
isLocked = false;
} else {
try {
lockFile.createNewFile();
isLocked = true;
} catch(IOException ioex) {
isLocked = false;
}
}
}
return isLocked;
}
用于测试的线程类
class AThread extends Thread {
String name;
public AThread(String name) {
this.name = name;
}
@Override
public void run() {
File f = new File("C:\\TEMP\\DIRECTORY");
System.out.println(name + ": " + Util.acquireFolderLock(f));
}
}
以及启动线程的主要方法
public static void main(String[] args) throws Exception {
for(int i = 1; i <= 100; i++) {
(new AThread("Thread-->" + i)).start();
}
}