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

yoo*_*nsi 6 java applet multithreading

我正在阅读sun java教程,我在这里看到了这个页面:

如何制作一个小程序

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

   //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();
}
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 7

execute是一种方法SwingWorker.你所看到的是一个匿名类被实例化并execute立即调用它的方法.

我不得不承认我有点惊讶的是代码编译,但是,因为它似乎是分配的结果executeworker变量,并且该文档告诉我们,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
    }

};
Run Code Online (Sandbox Code Playgroud)

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

SwingWorker worker = tmp.execute();
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)