1.定义一个final Object 的锁对象
/**
* 脚本执行是否结束
*/
private static boolean complete = false;
/**
* final Object 锁对象
*/
private static final Object lock = new Object();
2.线程A执行脚本任务
对lock对象加锁,在执行完任务之后通知其余线程,并释放锁
// 执行脚本
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
if (list.size() == 0){
MainFrame.appendTextArea("ERROR 所选文件或目录下无sql脚本,请重新选择");
return;
}
synchronized (lock){
MainFrame.appendTextArea("所选目录下共 "+list.size()+" 个脚本");
for (File files : list){
MainFrame.appendTextArea("开始执行脚本:"+files.getName());
if (!execute(files,mysqlConnect)){
break;
}
}
complete = true;
lock.notifyAll();
}
}
});
thread.start();
3.线程B在脚本执行结束之后删除脚本
// 删除
Thread delete = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
while (!complete){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
FileUtils.deleteAllFiles(targetFile);
}
}
});
delete.start();