2016-11-26 33 views
0

我想在执行cmd命令时获得响应JavaFX图形界面。
我正在执行的命令如下。多线程使用Callable,同时有一个响应图形界面

youtube-dl.exe --audio-format mp3 --extract-audio https://www.youtube.com/watch?v=l2vy6pJSo9c 

正如你看到的,这是一个YouTube,下载该转换YouTube链接到一个mp3文件。 我想要在第二个线程中执行此操作,而不是在主FX线程中执行。

我已经通过实现类StartDownloadingThread中的接口Callable解决了这个问题。

@Override 
public Process call() throws Exception { 
    Process p = null; 
    p = ExecuteCommand(localCPara1, localCPara2, localDirectory).start(); 
    try { 
     Thread.sleep(30); 
    }catch (InterruptedException e){} 
    return p; 
} 

的方法,只是ExecuteCommand返回一个ProcessBuilder对象。

我尝试使用Thread.sleep使程序返回到主线程,从而使应用程序响应。不幸的是,该计划仍然冻结。

这是如何调用方法调用。

ExecutorService pool = Executors.newFixedThreadPool(2); 
StartDownloadingThread callable = new StartDownloadingThread(parameter1, parameter2, directory); 
Future future = pool.submit(callable); 
Process p = (Process) future.get(); 
p.waitFor(); 

如何使用界面Callable使我的GUI响应?

回答

0

使用执行程序仅运行一项任务,以便使用在提交任务时返回的Futureget方法实际上不会释放原始线程以继续执行其他任务。之后你甚至会在原始线程上使用waitFor方法,这可能比您在Callable中做的任何事情都要花费更多的时间。

为此,Task class可能更适合,因为它允许您使用事件处理程序处理应用程序线程上的成功/失败。

另请确保在完成提交任务后关闭ExecutorService

Task<Void> task = new Task<Void>() { 
    @Override 
    protected Void call() throws Exception { 
     Process p = null; 
     p = ExecuteCommand(localCPara1, localCPara2, localDirectory).start(); 

     // why are you even doing this? 
     try { 
      Thread.sleep(30); 
     }catch (InterruptedException e){} 

     // do the rest of the long running things 
     p.waitFor(); 
     return null; 
    } 
}; 
task.setOnSucceeded(event -> { 
    // modify ui to show success 
}); 

task.setOnFailed(event -> { 
    // modify ui to show failure 
}); 
ExecutorService pool = Executors.newFixedThreadPool(2); 

pool.submit(task); 

// add more tasks... 

// shutdown the pool not keep the jvm alive because of the pool 
pool.shutdown(); 
+0

我实际上正在阅读以下教程。 https://www3.ntu.edu.sg/home/ehchua/programming/java/j5e_multithreading.html#zz-7.5 关于如何解决无响应用户界面。该文章的第7部分显示了如何通过使用Callable来实现它。作者使用Thread.sleep()将控制权返回给主线程。 – Mnemonics

相关问题