繁体   English   中英

等到线程结束

[英]Wait until the thread finish

我有一个 function 有内部线程做某事

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();
}

animation function 我在更新板 function 中召唤,然后执行 i++。 我想让 function 动画在线程结束之前不要继续 I++

animate功能中,我使用了来自 swing 的repaint() function,当我尝试使用.join()时,它的块repaint()线程。

public static void updateBoard(int column, Image image) {
    int i = 0;
    animate(column,image);
    i++;
}

像这样:

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

t.join();

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

您已经有一个执行updateBoard()方法的线程。 让这个线程是T1
您调用animate()并创建另一个线程,让该线程为 T2 . Now as per your question, you want to have T1 . Now as per your question, you want to have T1T2完成执行之前不要进一步运行。

Thread.java定义了一个方法join() ,它允许一个线程等待另一个线程完成。 在您的代码中,可以这样做。

static Thread animationThread = new Thread(new Runnable() {
    public void run() {
        try {
                /* Code */
                Thread.sleep(500);
        } catch (InterruptedException ex) {}
    }
});
public static void updateBoard(int column, Image image) {
    int i = 0;
    animate(column,image);
    animationThread.join(); // this will make the thread executing updateBoard to wait until the completion of animationThread.
    i++;
}
public static void animate(int column,Image image){
    animationThread .start();
}

但是现在每件事都一个接一个地运行,在这种情况下,有两个线程是没有用的。 这类似于

public static void updateBoard(int column, Image image) {
    int i = 0;
    animate(column,image);
    i++;
}
public static void animate(int column,Image image){
     try {
                /* Code */
                Thread.sleep(500);
        } catch (InterruptedException ex) {}
}

在这种情况下,除非 animate 方法完成(没有第二个线程),否则 i++ 将不会被执行。 因此,对于您问题中的用例,为动画设置单独的线程是没有意义的,它只会增加创建单独线程和上下文切换的开销。 尽管为 animation 设置一个单独的线程似乎是个好主意,但为此您必须重新构建您拥有的程序,因为逻辑基于并行执行,因此拥有多个线程是有意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM