我有两个扩展线程的类,一个从文件夹读取,另一个重命名该文件夹中的文件。我的问题是我理想地希望课程轮流阅读,但似乎我的作家班不时地跳枪,我不知道为什么。在我的阅读器类中,run方法如下。虽然时间在截止期内,但脚本运行了一个小时"执行以下操作
while(cTime.before(cutOff))
{
File[] paths;
ArrayList<String> names = new ArrayList<String>();
GenericExtFilter filter = new GenericExtFilter(ext);
paths = f.listFiles(filter);
Arrays.sort(paths, new Comparator<File>(){
public int compare (File a, File b){
return (int) (a.lastModified() - b.lastModified());
}
});
for(int j=0;j<paths.length;j++){
names.add(paths[j].getName());
}
if(!names.isEmpty())
if(!names.contains("jobcard.inp"))
{
dObj.setToken(paths[0]);//set the token as the file that needs to be renamed
cTime = new Time(date1.getTime());
}
else{
try {
System.out.println("sleep");
Thread.sleep(30*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在我的编写器类中,我只是简单地重命名由get标记传递的文件,但是在这个类中,它似乎会被通知并运行并尝试查找已经重命名的文件&#34; no这样的文件例外&#34;
while(cTime.before(cutOff))
{
d.getToken(this);
source=path.toPath();
try {
Files.move(source, source.resolveSibling("jobcard.inp"));
cTime = new Time(date1.getTime());
Thread.sleep(30*1000);
} catch (IOException | InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
最后,我有这两个类的持有者,它们具有同步方法
package reader;
import java.io.File;
import java.sql.Time;
import java.util.Calendar;
public class DataStore {
File path= null;
private int turn=0;
protected synchronized void setToken(File paths) {
while(turn!=0){
try{
wait();
}catch(InterruptedException ie){}
}
path = paths;
turn = 1-turn;
notify();
return;
}
protected synchronized void getToken(InpWriter inpWriter){
while(turn ==0){
try{
wait();
}catch(InterruptedException ie){
}
}
System.out.println(turn);
inpWriter.makeFile(path);
turn = 1-turn;
notify();
return;
}
}