アドバンスアプリケーションでは、いくつかの条件を満足するまで処理を一時中断させなければならないことがあります。org.zkoss.zk.ui.ExecutionsクラスのwaitとnotifyとnotifyAllメソッドはこの目的のために作られました。
イベントリスナが自身を一時中断させるにはwaitメソッドを使用します。アプリケーションの条件が満足したら、他のスレッドはnotify又はnotifyAllでそれを呼び起こします。モーダルダイアログはこのメカニズムを使った代表的な例です。
public void doModal() throws InterruptedException { ...Executions.wait(_mutex); //suspend this thread, an event processing thread} public void endModal() { ... Executions.notify(_mutex); //resume the suspended event processing thread }
これらの使用はjava.lang.Objectクラスのwait、notifyとnotigyAllと同じです。しかし、イベントリスナをjava.lang.Objectクラスのメソッドを使って中断や再開処理をすることはできません。さもなければ、関連したデスクトップのすべてのイベント処理はコントロールできなくなります。
Javaオブジェクトのwaitとnotifyとは違って、synchronized ブロックでExecutionsのwaitとnotifyを含むかは自由です。上記のケースでは競合問題にはなりえないので、ブロックを使わなくても結構です。しかし、競合状態になる可能性があれば、Javaオブジェクトのwaitとnotifyを処理するのと同じようにsynchronized ブロックを使います。
//Thread 1 public void request() { ... synchronized (mutex) { ...//start another thread Executions.wait(mutex); //wait for its completion } } //Thread 2 public void process() { ... //process it asynchronously synchronized (mutex) { Executions.notify(mutex); } }