java 在开始另一个方法之前等待方法完成的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11416476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:01:33  来源:igfitidea点击:

Simple way to wait for a method to finish before starting another one

javamultithreadinguser-interface

提问by user573382

I'm not familiar at all with Java threading :(. I have this class which, when called, constructs a new window (draw() method). The drawGUI() calls a processing method at the end (compare() method).

我对 Java 线程一点都不熟悉 :(。我有这个类,它在调用时会构造一个新窗口(draw() 方法)。drawGUI() 最后调用一个处理方法(compare() 方法) .

basically the structure is

基本上结构是

public static void draw() {
    // draws stuff


    compare();
}

The problem is that the window drawn by drawGUI() has some major visual artifacts till the processing (compare() ) is over.

问题是 drawGUI() 绘制的窗口在处理 (compare() ) 结束之前有一些主要的视觉伪影。

What is the simplest way I can implement to launch compare() after draw() has finished executing? Thank you

在 draw() 完成执行后,我可以实现启动 compare() 的最简单方法是什么?谢谢

采纳答案by Ovi Tisler

The simplestway is to just put your draw()code inside an asyncExec()inside your thread at the end

最简单的办法是只要把你的draw()代码中的asyncExec()你的线程里面末

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

    //do long running blocking bg stuff here
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            draw();
        }   
    }
}).start();
new Thread(new Runnable() {
public void run() {

    //do long running blocking bg stuff here
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            draw();
        }   
    }
}).start();

回答by Thor84no

Assuming that the reason you're getting the artefacts is that draw()hasn't had a chance to return, you can use a Thread.

假设您获得人工制品的原因是draw()没有机会返回,您可以使用Thread.

final T parent = this;
new Thread(new Runnable() {
    public void run() {
        parent.compare();
    }
}).start();

(Where T is the type of the class that has your compare method).

(其中 T 是具有您的比较方法的类的类型)。