私はいくつかの激しい数学計算(行列、ベクトルなどの配列)を行うプロジェクトに取り組んでいるので、当然、作業をジョブに分割し、それらをCompletionServiceに送信して、作業を並行して実行します。
各ジョブオブジェクトは、イベントを起動して、ジョブの開始、終了、進行、および/または失敗時にアプリケーションに通知できます。
現在、各ジョブはイベントリスナーのリスト全体へのハンドルを受け取り、単純に反復処理して、イベントオブジェクトを各ジョブに渡します(同じスレッド内)。これは私には合わないので、カスタムイベント/リスナーを使ってこの種のことを他の人に体験してもらいたいと思います。
イベントをGUIスレッドに送信する必要がありますか?一部のリスナーはGUIに関連している場合とそうでない場合があります。コードのユーザーに、次のようにイベントをGUIスレッドに手動で送信する必要がないようにします。
public class MyFooEventListener implements FooEventListener {
public void notifyJobStarted(FooEvent evt) {
// I want to avoid having users of my library write the following, right?
SwingUtilities.invokeLater(new Runnable(){
// update GUI here.
});
}
}
これは学校での研究プロジェクトのためのものであるため、私は自分のEventQueueを作成してもかまいません。また、並行性の良い演習になると思います。イベント駆動型システムを実装する「適切な」方法、イベントを適切に発生させる方法などを理解しようとするだけです。記事/チュートリアルへのリンクやハウツーも大歓迎です。
ありがとう!
編集:
My event model has multiple event types, such as JobStartedEvent
, JobEndedEvent
, JobProgressEvent
, etc. Is this a bad approach? Should I have a single event type, and if so, how do I pass information to the listeners that is not common to all events? Example: I want to pass a double in the range [0-1] for the progress event, but that is not applicable for an event like JobFailureEvent. What's the best approach to handling this?
I could put the extra information in the "source" object itself, but my source objects are the Job objects themselves, and it doesn't sit well with me to "leak" references to the job object, especially while it is running:
FooJob jobObject = (FooJob)event.getSource();
int progressPercent = jobObject.getCurrentProgress() * 100;
progressLabel.setText(progressPercent + "%");