有一个外部程序可以创建XML文件,但它可能需要一段时间才能创建。我需要我的Java程序等到文件存在后再继续。
我已经阅读了一些关于同步块的知识,我读到我可以这样做:
synchronized(this) {
while (!file.exists) { this.wait(); }
}老实说,我真的不太了解同步任务,所以我想知道我是否在正确的轨道上,或者我是否走错了路。
发布于 2015-04-07 21:21:59
所以我使用的是一个while循环,它检查文件是否不存在。如果没有,我会让线程休眠一秒钟。它似乎工作正常。谢谢你的帮助。
发布于 2015-04-07 21:28:01
解决这个问题的典型方法是让XML编写器创建XML文件,在创建完成后,它应该创建第二个文件,说明工作已经完成。
您的java程序应该侦听是否存在.done文件,而不是XML文件。
但是,如果您对XML编写应用程序没有任何控制,则不会起作用。
发布于 2015-04-06 22:46:53
在我看来,你应该有一些东西来通知线程。下面是我的例子。
public class Test {
File file;
public Test(File file){
this.file = file;
}
public void findFile(){
synchronized(this){
while(!file.exists()){
try {
System.out.println("before wait:");
this.wait();
System.out.println("after wait:");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void createFile(){
synchronized(this){
try {
System.out.println("before create a new file:");
file.createNewFile();
System.out.println("after create a new file:");
this.notify();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
Test t = new Test(new File("/Users/yehuizhang/Desktop/uttp.txt"));
Thread t1 = new Thread(new FindFile(t));
Thread t2 = new Thread(new CreateFile(t));
t1.start();
t2.start();
}
}
class FindFile implements Runnable{
Test t;
public FindFile(Test t){
this.t = t;
}
@Override
public void run(){
t.findFile();
}
}
class CreateFile implements Runnable{
Test t;
public CreateFile(Test t){
this.t = t;
}
@Override
public void run(){
t.createFile();
}
}https://stackoverflow.com/questions/29472969
复制相似问题