我想在按钮内执行多个方法,但有些方法需要更少的时间,有些需要更多的时间来处理,我希望它们以特定的顺序运行它们,因为一种方法适用于另一种方法的输出。我的按钮执行如下:-
{
Basic b = new Basic();
b.method1(); //Normal processing
b.method2(); //Normal processing
b.method3(); //Heavy processing takes a lot of time like 5 to 10sec
b.method4(); //Basic processing
b.method5(); //Medium Processing FileHandling(works on 5 file)
}
所以发生的事情是,一切都很完美,直到执行方法 2 为止,但随着方法 3 的到来,一切都变得一团糟。所以我认为发生的事情是我的方法 3 被跳过,方法 4 和方法 5 被执行结束给我一个空指针异常,因为它们取决于从 method3 的执行中接收到的数据。
有人可以告诉我如何确保我的方法 4 和 5 仅在我的方法 3 完成后运行,仅供引用,我的方法 3 包含来自不同类的 2 个方法,一个方法生成一些脚本,另一个方法执行它,该方法采用真实的脚本自从它使用 bash shell 以来已经有很长时间了。
P.S.-当我的按钮执行完成时,我看到我的 method3 没有执行任何类似已被跳过的操作。
代码:-
public void method3(String abstarpath,String filename,String parapth)
{
try{
String cmd1 = "tar xzf "+abstarpath;
String cmd2 = "mv "+ parapth+"/"+filename +" /home/apoorv/Desktop/";
txtarea.append("#"+cmd1+"\n");
txtarea.append("#"+cmd2+"\n");
executeCommands(cmd1, cmd2);
}catch(Exception e){
txtarea.append("#"+e+"\n");
e.printStackTrace();
}
txtarea.append("\n");
}
public void executeCommands(String cmd1,String cmd2) throws IOException {
File tempScript = createTempScript(cmd1,cmd2);
try {
ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());
pb.inheritIO();
Process process = pb.start();
process.waitFor();
} catch (InterruptedException e) {
txtarea.append("#"+e+"\n");
e.printStackTrace();
} finally {
tempScript.delete();
}
}
public File createTempScript(String cmd1,String cmd2) throws IOException {
File tempScript = File.createTempFile("script", null);
Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
tempScript));
PrintWriter printWriter = new PrintWriter(streamWriter);
printWriter.println("#!/bin/bash");
printWriter.println(cmd1);
printWriter.println(cmd2);
printWriter.close();
return tempScript;
}
最佳答案
查看您的代码,您遇到的问题似乎与并发性没有任何关系。问题是您的 main 方法不知道 methodX()
方法是否成功完成。
您可以做的是将异常处理移至主方法:
try {
Basic b = new Basic();
b.method1(); //Normal processing
b.method2(); //Normal processing
b.method3(); //Heavy processing takes a lot of time like 5 to 10sec
b.method4(); //Basic processing
b.method5(); //Medium Processing FileHandling(works on 5 file)
}
catch (Exception e) {
// error handling
}
(当然,您必须从其他方法中删除异常处理)。
然后,一旦其中一个方法抛出异常,其余方法就会被跳过并执行异常处理程序。
关于java - 一次一个地执行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38178677/