加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

这个java .execute()方法调用是什么意思?

发布时间:2020-12-15 00:59:08 所属栏目:Java 来源:网络整理
导读:我正在阅读sun java教程,我在这里看到了这个页面: How to Make an Applet 在标题“小程序中的线程”下,我找到了这段代码: //Background task for loading images. SwingWorker worker = (new SwingWorkerImageIcon[],Object() { public ImageIcon[] doInBa
我正在阅读sun java教程,我在这里看到了这个页面:

How to Make an Applet

在标题“小程序中的线程”下,我找到了这段代码:

//Background task for loading images.
    SwingWorker worker = (new SwingWorker<ImageIcon[],Object>() {
            public ImageIcon[] doInBackground() {
                final ImageIcon[] innerImgs = new ImageIcon[nimgs];
            ...//Load all the images...
            return imgs;
        }
        public void done() {
            //Remove the "Loading images" label.
            animator.removeAll();
            loopslot = -1;
            try {
                imgs = get();
            } ...//Handle possible exceptions
        }

    }).execute();
}

首先,我是新的,所以如果这是一个愚蠢的问题,我很抱歉.但是我从来没有听说过“.excecute()”.我不明白,我无法从谷歌找到任何关于它的东西.我看到这里是……一个匿名的内部阶级? (请纠正我),它正在启动一个加载图像的线程.我以为通过调用start()来调用run()方法?请帮我清除这种困惑.

解决方法

execute是SwingWorker的一种方法.您所看到的是 anonymous class被实例化并立即调用其execute方法.

我不得不承认我对代码编译感到有些惊讶,因为它似乎是将执行结果赋给worker变量,文档告诉我们execute是一个void函数.

如果我们稍微解构一下代码,那就更清楚了.首先,我们创建一个扩展SwingWorker的匿名类并同时创建它的一个实例(这是括号中的大部分):

SwingWorker tmp = new SwingWorker<ImageIcon[],Object>() {
    public ImageIcon[] doInBackground() {
            final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        ...//Load all the images...
        return imgs;
    }
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } ...//Handle possible exceptions
    }

};

然后我们调用execute并将结果赋给worker(在我看来,这不应该编译):

SwingWorker worker = tmp.execute();

更新:事实上,我尝试了它,它doesn’t compile.所以不是很好的示例代码.这将编译:

SwingWorker worker = new SwingWorker<ImageIcon[],Object>() {
    public ImageIcon[] doInBackground() {
            final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        ...//Load all the images...
        return imgs;
    }
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } ...//Handle possible exceptions
    }

};
worker.execute();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读