2017-03-01 45 views
2

我已经写了一个脚本在java中使用我正在执行.exe文件来安装应用程序之后,我复制通过安装生成的文件到远程位置。但问题是在安装完成之前,下一步将文件复制到机器位置正在发生。因此导致粘贴空文件,因为安装没有完成,因此文件存在。我如何才能停止我的过程,直到前一步骤结束。我试图使用thread.sleep(10000),但这并不是帮助,因为安装时间可能会有所不同。我怎样才能停止我的过程,直到前面的步骤结束

public class threadJoin { 
public static void main(String s[]){ 
    Runnable r = new Runnable() { 
     @Override 
     public void run() { 
      File f = new File("C:\\D\\EVProject\\"); 

      FilenameFilter textFilter = new FilenameFilter() { 
      public boolean accept(File dir, String name) { 
      return name.startsWith("EVProject"); 
    } 
}; 

File[] files = f.listFiles(textFilter); 

for (File file : files) {  

       try { 
        String filexy = file.getCanonicalPath(); 
        System.out.print(filexy); 
        Runtime.getRuntime().exec(filexy); 
        //Thread.sleep(10000); 
       } catch (IOException ex) { 
        Logger.getLogger(threadJoin.class.getName()).log(Level.SEVERE, null, ex); 
       } 
     } 


     } 
    }; 
    Runnable r2 = new Runnable() { 
     @Override 
     public void run() { 
      String l ="C:\\Program Files\\PD "; 
      String m = "C:\\0.0.9.8"; 
      File srcDir = new File(l); 
      File destDir = new File(m); 
    try {   
     FileUtils.copyDirectory(srcDir, destDir); 
    } catch (IOException e) { 
    } 
      throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
     } 
    }; 


    Thread t1= new Thread(r); 
    Thread t2 = new Thread(r2); 
    t1.start(); 
    try{ 
     t1.join(); 
    }catch(InterruptedException e){   
    } 
    t2.start(); 

} 

}

this is error what i am getting by using join()

+0

你能显示代码吗? –

+0

您的程序如何知道安装完成? –

+0

它不检查安装是否完成。我的程序只是调用.exe文件@DanielWiddis – BleedCode

回答

1

的Runtime.exec返回一个进程句柄。您可以使用此进程句柄来等待进程结束。该句柄还可以给你一个int值,表明该过程是否成功,但这需要你测试,因为它可能会因实现而有所不同。

在你的情况 - 尝试下面

过程MYP =调用Runtime.getRuntime()EXEC(filexy);
int isTrue = myP.waitFor();

看看是否有帮助。

+0

thnx它工作:)。还有一个问题,如果我将这些文件从一个位置复制粘贴到另一个位置,那么在这种情况下,程序也不应该移动到下一步,直到粘贴完成。 Plzzz回答:) – BleedCode

+0

如果您使用Java API移动文件,这应该不是问题。 – PankajT

+0

我正在使用apache-common-io来复制文件 – BleedCode

0

也许悠可以使用join方法join(),这样的事情:

 Runnable task1 =() -> { 
      for (int i = 0 ; i < 5 ; i++) { 
       System.out.println("task1..." + i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) {} 
      } 
     }; 

     Runnable task2 =() -> { 
      for (int i = 0 ; i < 5 ; i++) { 
       System.out.println("task2..." + i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) {} 
      } 
     }; 

     Thread th1 = new Thread(task1); 
     Thread th2 = new Thread(task2); 

     th1.start(); 
     try { 
      th1.join(); 
     } catch (InterruptedException e) {} 

     th2.start();