有一个外部程序会创建一个XML文件,但可能需要一段时间来完成。我需要我的Java程序在继续执行之前等待文件存在。
我已经阅读了一些关于synchronized块的内容,并且我知道我可以做类似于下面这样的事情:
synchronized(this) {
while (!file.exists) { this.wait(); }
}
说实话,我对同步任务并不是很了解,所以我想知道我是否走在了正确的轨道上,或者我完全错了。
有一个外部程序会创建一个XML文件,但可能需要一段时间来完成。我需要我的Java程序在继续执行之前等待文件存在。
我已经阅读了一些关于synchronized块的内容,并且我知道我可以做类似于下面这样的事情:
synchronized(this) {
while (!file.exists) { this.wait(); }
}
说实话,我对同步任务并不是很了解,所以我想知道我是否走在了正确的轨道上,或者我完全错了。
WatchService
,而不是循环轮询方法。摆脱古老且大多数人不赞成的习惯对您有好处。 - Boris the Spiderpublic 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();
}
}
等待之前: 创建新文件之前: 创建新文件之后: 等待之后:
- uttpcreateFile
在外部程序中,无法通知findFile
线程。 - Colonel Thirty TwoObject.notify
。 - Colonel Thirty Two
synchronized
。你可以选择:1)等待程序完成,或在程序写入文件时从程序中写入stdout; 或者2)使用WatchService
跟踪目录更改。 - Boris the Spidersynchronized
与多线程程序有关。其次,外部程序是独立于您的Java程序运行的,还是您的Java程序启动了这个外部程序? - Alexander R.