嗨我试图阻止一个线程并阻止FFmpeg继续在bachground中。因此,当用户单击取消按钮时,它会停止线程并停止FFmpeg我将首先显示我的类MashRocks,该按钮调用方法,所以我想这就是我应该显示的所有内容。
package my.mashformcnts;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
*
* @author brett
*/
public class MashRocks {
public static Thread startThread(MashFormCnts mashFormCnts) throws IOException {
ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", "C:\\Users\\brett\\Documents\\Telegraph_Road.mp4", "C:\\Users\\brett\\Documents\\out.mp4");
final Process p = pb.start();
// create a new thread to get progress from ffmpeg command , override
// it's run method, and start it!
Thread t = new Thread() {
@Override
public void run() {
Scanner sc = new Scanner(p.getErrorStream());
// Find duration
Pattern durPattern = Pattern.compile("(?<=Duration: )[^,]*");
String dur = sc.findWithinHorizon(durPattern, 0);
if (dur == null) {
throw new RuntimeException("Could not parse duration.");
}
String[] hms = dur.split(":");
double totalSecs = Integer.parseInt(hms[0]) * 3600 + Integer.parseInt(hms[1]) * 60 + Double.parseDouble(hms[2]);
System.out.println("Total duration: " + totalSecs + " seconds.");
// Find time as long as possible.
Pattern timePattern = Pattern.compile("(?<=time=)[\\d:.]*");
String match;
String[] matchSplit;
//MashForm pgbar = new MashForm();
while (null != (match = sc.findWithinHorizon(timePattern, 0))) {
matchSplit = match.split(":");
double progress = (Integer.parseInt(matchSplit[0]) * 3600 + Integer.parseInt(matchSplit[1]) * 60 + Double.parseDouble(matchSplit[2])) / totalSecs;
int prog = (int) (progress * 100);
mashFormCunts.setbar(prog);
}
}
};
t.start();
return t;
}
//This works but is it correct??
public synchronized static Thread stop(Thread t){
Runtime.getRuntime().exec("taskkill /F /IM ffmpeg.exe");
t = null;
//t.interrupt();
//im not sure what else to do?
}
}
同样在我的表单中,这个代码我用来获取Thread并将其发送到方法
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Thread t = Thread.currentThread();
System.out.print(t);
MashRocks.stop(t);
}
答案 0 :(得分:1)
你是对的,有更好的方法。您应该将Process值存储在某处,并使用Process.destroyForcibly()来终止它。根据您发布的代码,您可能希望将Thread子类化,这样您就可以存储可以轻松返回的Process。
启动时,您还需要存储对自定义Thread对象的引用。如果一次只能有一个,则可以使用单例来存储单个实例。如果可能有多个,您将需要创建活动线程的列表或注册表。