import javafx.concurrent.Task;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
public class LoadFilePool extends Task {
private String projectPath; // 项目路径
private List<String> fileList; // 所有文件路径
private ThreadPoolExecutor threadPool;
private CountDownLatch countDownLatch;
public LoadFilePool() {
/** 使用重新提交的拒绝策略 */
this.threadPool = new ThreadPoolExecutor(3,
20,
120,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(20),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
public LoadFilePool(String projectPath) {
this();
this.updateMessage(Words.string(R.loadingAnalysis));
this.projectPath = projectPath;
}
@Override
protected Object call() {
this.fileList = ProjectFileUtil.getFileList(this.projectPath); // 获取所有文件路径列表
this.countDownLatch = new CountDownLatch(this.fileList.size());
Iterator<String> iterator = this.fileList.iterator();
while (iterator.hasNext()) {
String filePath = iterator.next();
this.concurrentRun(new LoadFileTask(this.projectPath, filePath) {
@Override
public void run() {
try {
File file = new File(this.getFilePath());
String name = file.getName();
updateMessage(name);
updateProgress(fileList.size() - countDownLatch.getCount(), fileList.size());
// 加载到内存中-读取并文件
ProjectFileUtil.loadFileInformation(this.getProjectPath(), this.getFilePath());
} catch (Exception e) {
} finally {
countDownLatch.countDown();
}
}
});
}
this.shutdown();
return null;
}
public void concurrentRun(Runnable task) {
try {
if (task != null) {
if (!this.threadPool.isShutdown()) {
this.threadPool.submit(task);
}
}
} catch (Exception e) {
}
}
public void shutdown() {
try {
this.countDownLatch.await(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
ProjectFileMemory.getFileMemory(this.projectPath).sortFilePath(); // 内存中排序
Logger.info("Load file pool has %s failed.", this.countDownLatch.getCount());
this.threadPool.shutdown();
// 无论成功失败,进度都结束
this.updateProgress(100.0, 100.0);
}
}
public void close() {
this.threadPool.shutdown();
}
public void shutdownNow() {
this.threadPool.shutdownNow();
}
abstract private class LoadFileTask implements Runnable {
private String projectPath;
private String filePath;
public String getProjectPath() {
return this.projectPath;
}
public String getFilePath() {
return this.filePath;
}
public LoadFileTask(String projectPath, String filePath) {
this.projectPath = projectPath;
this.filePath = filePath;
}
}
}
LoadFilePool loadFilePool = new LoadFilePool(this.projectPath);
// 进度条显示
this.progressBar.progressProperty().unbind();
this.progressBar.progressProperty().bind(loadFilePool.progressProperty());
// 执行信息显示
this.labelContent.textProperty().unbind();
this.labelContent.textProperty().bind(loadFilePool.messageProperty());
new Thread(loadFilePool).start();
loadFilePool.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, new EventHandler() {
@Override
public void handle(Event event) {
close();
}
});