4

HTTP コンテンツのダウンロードなど、多数のタスクのためにワーカー スレッドを生成する J2ME プロジェクトに取り組んでいます。基本的なスレッド レイアウトは、ほとんどの Java アプリと似ています。メインの UI スレッドと、バックグラウンドで処理を行うために生成されたワーカー スレッドがあります。私の質問は、ワーカー スレッドで発生する例外を処理する最善の方法は何ですか?

私は通常、ほとんどの例外は可能な限り浸透させるべきであるという設計上の理論的根拠に従います。シングル スレッド アプリを作成するときは、例外を UI レイヤーまで浸透させてから、エラー ダイアログでユーザーに報告するのが一般的です。マルチスレッド アプリに同様の方法はありますか? 私にとって最も直感的な方法は、Thread.run() で例外をキャッチし、UI スレッドで invokeLater を呼び出してダイアログで報告することです。ここで見られる問題は、ワーカー スレッドが途中で終了する以外に、このアプローチではエラーが発生したことを UI スレッドに実際に通知しないことです。いわばスレッド間で例外をスローする明確な方法がわかりません。

ありがとう、アンディ

4

2 に答える 2

7

ワーカーに UI コードを詰め込まないでください。

/**
 * TWO CHOICES:
 * - Monitor your threads and report errors,
 * - setup a callback to do something.
 */
public class ThreadExceptions {

    /** Demo of {@link RunnableCatch} */
    public static void main(String[] argv) throws InterruptedException {
        final Runnable bad = new NaughtyThread();
        // safe1 doesnt have a callback
        final RunnableCatch safe1 = new RunnableCatch(bad);
        // safe2 DOES have a callback
        final RunnableCatch safe2 = new RunnableCatch(bad, new RunnableCallback() {
            public void handleException(Runnable runnable, Exception exception) {
                System.out.println("Callback handled: " + exception.getMessage());
                exception.printStackTrace();
            }

        });
        final Thread t1 = new Thread(safe1, "myThread");
        final Thread t2 = new Thread(safe2, "myThread");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        if (safe1.getException() != null) {
            System.out.println("thread finished with exceptions");
            safe1.getException().printStackTrace();
        }
        System.out.println("done");
    }


}

/** Throws an exception 50% of the time */
class NaughtyThread implements Runnable {
    public void run() {
        try {
            if (Math.random() > .5) {
                throw new RuntimeException("badness");
            }
        } finally {
            System.out.println("ran");
        }
    }
}

/** Called when an exception occurs */
interface RunnableCallback {
    void handleException(Runnable runnable, Exception exception);
}

/**
 * Catches exceptions thrown by a Runnable,
 * so you can check/view them later and/or
 * deal with them from some callback.
 */
class RunnableCatch implements Runnable {

    /** Proxy we will run */
    private final Runnable _proxy;

    /** Callback, if any */
    private final RunnableCallback _callback;

    /** @guarded-by(this) */
    private Exception _exception;

    public RunnableCatch(final Runnable proxy) {
        this(proxy, null);
    }

    public RunnableCatch(final Runnable proxy, RunnableCallback target) {
        _proxy = proxy;
        _callback = target;
    }

    public void run() {
        try {
            _proxy.run();
        } catch (Exception e) {
            synchronized (this) {
                _exception = e;
            }
            if (_callback != null) {
                _callback.handleException(_proxy, e);
            }
        }
    }

    /** @return any exception that occured, or NULL */
    public synchronized Exception getException() {
        return _exception;
    }
}
于 2008-11-16T04:17:20.350 に答える
0

Stuph が提供したもの以外の別のオプションは、スレッド ローカルに例外を設定することです。その例外がクリアされる前に別の例外が発生すると、アサートが発生します。これにより、少なくとも誰かが例外に気付き、処理する機会が得られます。

于 2008-11-16T04:28:55.193 に答える