我正在研究java中的一个简单的文件阅读器工具,我面临着抽象类上的任务声明问题。我在UI中有一个“运行”按钮,它触发一个方法“启动”以从文件中读取和写入信息。我使用AbstractClass的原因是因为我有不同的Impl。因为我对同一个文件有不同的待遇。 ex bellow:
抽象类
public abstract class AbstractService {
ArrayList<Info> info = new ArrayList<Info>();
public AbstractService() {
super();
}
protected void start() {
run();
finish();
}
protected void run() {
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
final List<File> files = in.getFiles();
for(File file : files) {
String filename = file.getName();
readLines(file);
}
finishWorkForSelect(filename);
return null;
}
};
new Thread(task).start();
}
protected void readLines(File file) {
//is Override in Impl class of a specific worker
}
protected void addData() {
//is Override in Impl class of a specific worker
}
protected void finishWorkForSelect(String filename) {
finishWorkForProcess(filename); //method Override in Impl class
}
protected void finish() {
finishWork();
writeData();
}
protected void writeData() {
//writing data from info arraylist
}
工作者实现类的示例:
public class WorkerOneServiceImpl extends AbstractService implements Service {
/**
* @see Service#process()
*/
@Override
public void process() {
super.start();
}
/**
* @see AbstractService#readLines(file)
*/
@Override
protected void readLines(File file) {
//calling addData()
}
@Override
protected void addData() {
//code
}
@Override
protected void finishWorkForProcess(filename) {
// Will create only on file for all processes
}
@Override
protected void finishWork() {
//calling for another method for creating excel file on one process
}
当我运行该工具时,主线程将通过所有这些方法,并且不会在.xlsx文件中写入任何内容。我尝试将synchronized关键字添加到Override readLines()方法但没有成功。通过添加将readLines()方法更改为:
进行相同的测试@Override
protected void readLines(File file) {
synchronized (AbstractService.class) {
//code
}
}
但又没有成功。我知道abstractclass不能是instanciate所以没有Object可以锁定。此外,如果我将writeData()中的代码移动到addData()方法中,它就可以工作。
是否有可能通过这个抽象类同步这些方法或者我错过了什么?