我有一个复制文件并给进度条进度的线程,我有一个方法停止文件流复制并杀死线程,我试图实现一个jOptionPanel yes_no来询问用户他们是否确定他们想要删除。但我需要能够暂停fileInputStream副本,直到线程停止或继续。线程等待,但文件副本继续。我怎样才能解决这个问题?任何帮助都会很棒
首先是我要暂停的主题
thr = new Thread("cool") {
@Override
public void run() {
while (running == true) {
try {
newWorkFileName();
long length = fileIn.length();
long counter = 1;
int r;
byte[] b = new byte[1024];
fin = new FileInputStream(fileIn);
fout = new FileOutputStream(fileOut);
tvConvertInterface.updateJLabel2("Creating File");
while ((r = fin.read(b)) != -1) {
counter += r;
fout.write(b, 0, r);
prog = (int) Math.round(100 * counter / length);
tvConvertInterface.updateJProgressbar1(prog);
}
fin.close();
fout.close();
tvConvertInterface.disableStopBtn();
tvConvertInterface.updateJLabel2("Work File Created");
running = false;
} catch (NullPointerException | IOException ex) {
tvConvertInterface.disableStopBtn();
tvConvertInterface.updateJLabel2("File is not valid");
Logger.getLogger(TvConvertGutts.class.getName()).log(Level.SEVERE, null, ex);
tvConvertInterface.updateJProgressbar1(0);
running = false;
}
}
}
};
接下来是我想要实现jOptionPanel的方法
public boolean terminate() throws IOException, InterruptedException {
synchronized (thr) {
thr.wait();//MAKES THREAD WAIT
//I NEED TO PAUSE THE FILESTREAM AND BE ABLE TO RESUME
}
int n = JOptionPane.showConfirmDialog(
null, "SURE YOU WANT TO DELETE?",
"Kill It Dude",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
fin.close(); //CLOSE INPUT STREAM
fout.flush();//FLUSH OUTPUT STREAM
fout.close(); //CLOSE OUTPUT STREAM
thr.interrupt();//KIILL THE THREAD
System.out.println(thr.getState());//PRINT STATE OF THREAD
TvConvertInterface bst = new TvConvertInterface(null, true);
bst.disableStopBtn();//SET PROGRESSBAR TO 0
} else if (n == JOptionPane.NO_OPTION) {
synchronized (thr) {
thr.notify();//DONT DELETE AND CONTINUE
}
} else {
System.out.println("spewin");
}
return false;
}
点击按钮调用此终止方法。来自名为TvConvertInterface的类
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
check.terminate();
} catch (IOException ex) {
Logger.getLogger(TvConvertInterface.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:1)
您错误地使用了JAVA并发API 。
object.wait()
将暂停当前线程,在这种情况下object
将用作监视器对象。
您需要做的是:
boolean shouldPauseThread
变量boolean stopThread
shouldPauseThread
变量并通知以前使用过的监控对象