如何cancel一个swing worker(续)

GD Star Rating
loading...

上一次谈到如何去cancel一个swing worker,今天在代码里又出了问题:即使使用swingWorker.cancel(true)仍然无法在sleep时中止线程。追了一下代码,最后在javax.swing.ImageIcon类里找到了原因:

protected void loadImage(Image image) {
    synchronized(tracker) {
        int id = getNextID();

        tracker.addImage(image, id);
	try {
	    tracker.waitForID(id, 0);
	} catch (InterruptedException e) {
	    System.out.println("INTERRUPTED while loading Image");
	}
        loadStatus = tracker.statusID(id, false);
	tracker.removeImage(image, id);

        width = image.getWidth(imageObserver);
	height = image.getHeight(imageObserver);
    }
}

其中第7行会抛出InterruptedException,而在第10行捕捉了该异常,导致InterruptedException无法抛到我的代码里。很典型的“eat-up exception”的例子。解决该问题可以在初始化ImageIcon前sleep一下,比如sleep(5),让interrupted状态在sleep中触发InterruptedException

原创内容,转载请注明: 转载自拈花微笑

本文链接地址: 如何cancel一个swing worker(续)

685

One comment

  • 2008 年 11 月 15 日 - 上午 1:49 | Permalink
    GD Star Rating
    loading...

    A smart trick.

  • 发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注

    *

    您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

    :wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:

    使用新浪微博登陆

    无觅相关文章插件,快速提升流量