java - 您如何在不卡住GUI的情况下等待Java中的线程完成?

标签 java android multithreading

我正在用Java在Eclipse中编写一个android游戏。主要目标是等待线程完成,然后将 boolean 值设置为true。原因是当用户单击按钮时,只有 boolean 值为true时,它才会运行。但是,当我调用方法时,它会创建一个线程并执行其操作,然后在完成时将 boolean 值设置为true。但是,它会在线程仍在运行时自动将 boolean 值设置为true,因此用户可以单击按钮(这会使事情有些困惑)。有没有一种方法可以等待线程完成而不冻结屏幕? (thread.join()似乎冻结了它)

任何帮助表示赞赏。

最佳答案

似乎您真的不需要等到线程完成后再继续,就我所知,您只需要在完成后就通知它,最简单的方法是将“回调监听器”对象传递给线程,并在完成后执行它,这将使您知道您已准备好继续,或者更好的方法是AsyncTask,它允许您在后台执行所有操作,并在完成后可以使用onPostExecute方法,希望对您有所帮助。

这是创建和添加回调的方式,当线程完成时,该回调将被通知:

//Create your callback listener interface...
public interface MyThreadListener{
    public void threadFinished();
}

//This is the method that runs some functionality in a separate thread
public void executeTaskInSeparateThread(final MyThreadListener listener){
    new Thread(new Runnable() {

        @Override
        public void run() {
            // DO your long task here...

            //Notify when done before leaving run method...
            listener.threadFinished();
        }
    }).start();
}

//Use it like this
//Create the implementation of the listener you want (this is something like what you usually do for buttons or any other android listener)
MyThreadListener listener = new MyThreadListener() {

    @Override
    public void threadFinished() {
        //Do whatever you want when notified...
        //NOTE: This method will be called on a separated thread too, you cannot modify views...
    }
};
executeTaskInSeparateThread(listener);

线程完成后,它将执行监听器并通知您完成...

问候!

关于java - 您如何在不卡住GUI的情况下等待Java中的线程完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793687/

相关文章:

java - 如何在 lambda 表达式中使用外部变量

java - 如何确定应用程序的方法计数?

Java 内存错误 : unable to create new native thread

java - 如何防止在 Spring 执行第二个查询?

java - 使用java的-XX :OnError option

android - 获取 styled 属性中使用的可绘制引用的资源 id

c# - 使用来自 Firebase 数据库表 Xamarin 的数据填充 Spinner

python - 从线程迁移到线程

java - 为什么使用 volatile 使 long 和 double atomic

java - double 局部变量打印为 0.0 而不是设置值