在主线程任务执行过程中需要等待方法执行完毕才能进行下一个任务操作,方法完成前会出现界面卡顿无法操作等情况。此时,我们应该一些耗时长的操作放入后台子线程执行。
【核心代码】
private void function() {
runFuction().execute();
}
private SwingWorker<Void, Void> runFuction() {
SwingWorker<Void, Void> print = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
//需要后台执行任务写在这
return null;
}
};
return print;
}
【示例代码】
public class TestWindow {
private JButton testBtn;
//触发点击时间
testBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (installBtn.isEnabled()) {
try {
test(project).execute();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
private SwingWorker<Void, Void> test(Project project) throws IOException {
SwingWorker<Void, Void> ans = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
//执行后台任务
Thread.sleep(10000)
return null;
}
};
return ans;
}
}