【发布时间】:2012-09-27 21:31:39
【问题描述】:
我编写了这个程序来测试mkdir() 失败的场景。为什么会失败?
有时效果很好,有时我得到:
无法创建 DIR :: myDir4 无法创建 DIR :: myDir4
最后我发现每个目录都被创建...
在每次测试中,我都会删除所有创建的目录。
我尝试了这个,因为在我的项目中有 100 个线程试图测试和创建这样的目录......并且也以同样的方式失败......
public class DFS {
static long time1 = System.currentTimeMillis();
public static void main(String a[]) {
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
new Thread(new CreteDir()).start();
}
}
class CreteDir implements Runnable {
public void run() {
//Object obj = new Object();
synchronized (this) {
if(System.currentTimeMillis() - DFS.time1 > 10) {
try {
this.wait();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
File f1 = new File("myDir1");
File f2 = new File("myDir2");
File f3 = new File("myDir3");
File f4 = new File("myDir4");
File f5 = new File("myDir5");
if (!f1.exists()&&!f1.mkdir()) {
System.out.println("Cannot create DIR :: "+f1.getName());
}
if (!f2.exists()&&!f2.mkdir()) {
System.out.println("Cannot create DIR :: "+f2.getName());
}
if (!f3.exists()&&!f3.mkdir()) {
System.out.println("Cannot create DIR :: "+f3.getName());
}
if (!f4.exists()&&!f4.mkdir()) {
System.out.println("Cannot create DIR :: "+f4.getName());
}
if (!f5.exists()&&!f5.mkdir()) {
System.out.println("Cannot create DIR :: "+f5.getName());
}
this.notifyAll();
}
}
}
【问题讨论】:
-
有时我收到消息无法创建 DIR :: myDir1 无法创建 DIR :: myDir2 我认为这是由于一个线程测试 dir 存在并且在 mkdir 操作之前其他线程创建 dir.. . 和 mkdir 操作上的当前线程收到此失败消息..
-
可能目录已经存在?
-
@Kamil...是的...这只是拼写错误...但是对于代码来说这不是问题...
-
synchronized (this)没有任何意义。在这种情况下,this将只能被一个线程访问。 -
一次运行几个线程试图创建相同的目录也没有任何意义......
标签: java multithreading mkdir