Reputation: 386
I have a thread that copies a file and give the progress bar the progress, I have a method the stops the filestream copy and kills the thread, I am trying to implement a jOptionPanel yes_no to ask the user if they are sure they want to delete. But i need to be able to pause the fileInputStream copy until the thread either stops or is continued. The thread waits but the file copy keeps going. how can i fix this? Any help would be great
First is the thread I want to pause
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;
}
}
}
};
Next is the Method that i want to implement the 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;
}
This terminate method is called by a button click. From a class called 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);
}
Upvotes: 0
Views: 61
Reputation: 9687
You are using the JAVA concurrency API incorrectly.
The object.wait()
will pause the current thread and the object
in this case would serve as a monitor object.
What you need to do is the following:
boolean shouldPauseThread
variableboolean stopThread
shouldPauseThread
variable and notify on the previously used monitor objectUpvotes: 1