等到线程完成

mat*_*tan 1 java swing multithreading

我有一个函数,它的内部线程可以做某事

public static void animate(int column,Image image)
{

    new Thread(new Runnable() {
        public void run() {
            try {

                    /* Code */
                    repaint();
                    Thread.sleep(500);
                    repaint();

            } catch (InterruptedException ex) {
            }
        }
    }).start();
}
Run Code Online (Sandbox Code Playgroud)

我在 updateBoard 函数中调用的动画函数,然后是 i++。我想让函数动画在线程结束之前不继续 I++

在函数内部,animate我使用repaint()了 Swing 中的函数,当我尝试使用.join()它的块repaint()线程时。

public static void updateBoard(int column, Image image) {
    int i = 0;
    animate(column,image);
    i++;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*n C 5

像这样:

Thread t = new Thread(new Runnable(){...});
t.start();

t.join();
Run Code Online (Sandbox Code Playgroud)

然而,这有点毫无意义。如果您要启动一个线程并立即阻塞等待它完成,您将不会获得任何并行性。您也可以只Runnable::run在当前线程中调用该方法......并避免创建/启动线程的(不是微不足道的!)开销。