2016-11-26 5 views
0

cmdコマンドを実行しているときに応答性の高いJavaFXグラフィカルインターフェイスを取得しようとしています。
実行しているコマンドは次のとおりです。応答可能なグラフィカルインターフェイスを使用しているときにCallableを使用したマルチスレッド

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

ご覧のとおり、YouTubeのリンクをmp3ファイルに変換するyoutube-downloaderです。 これは、メインのFXスレッドではなく、2番目のスレッドで実行します。

私は、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; 
} 
ProcessBuilder

だけオブジェクトを返すExecuteCommand方法。

私は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

executorを使用してgetメソッドを使用するだけで、タスクを実行するときに返されるFutureは、実際には元のスレッドを解放して他のタスクを続行しません。後で元のスレッドで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 Unresponsive User Interfaceの解決方法についてこの記事の第7章では、Callableを使用してどのように行うことができるかを示しています。作者はThread.sleep()を使ってメインスレッドに制御を返します。 – Mnemonics

関連する問題