与 UI 线程通信的网络线程

Network Thread to communicate with UI Thread

我在 Java 应用程序中为多线程创建了一个 class。

进口java.util.concurrent.Executor; 导入 java.util.concurrent.Executors;

public class AppThreads {

private static final Object LOCK = new Object();
private static AppThreads sInstance;
private final Executor diskThread;
private final Executor uiThread;
private final Executor networkThread;

private AppExecutors(Executor diskThread, Executor networkThread, Executor uiThread) {
    this.diskThread = diskThread;
    this.networkThread = networkThread;
    this.uiThread = uiThread;
}

public static AppExecutors getInstance() {
    if (sInstance == null) {
        synchronized (LOCK) {
            sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(4),
                    new MainThreadExecutor());
        }
    }
    return sInstance;
}

public Executor diskThread() {
    return diskThread;
}

public Executor networkThread() {
    return networkThread;
}

private static class MainThreadExecutor implements Executor {
    @Override
    public void execute(Runnable command) {
        command.run();
    }
}

}

我正在启动另一个线程

public void getUsers(AppThreads executors) {
executors.networkThread().execute(() -> {
    //Some DB operations
    //getting server response code  
HttpURLConnection con = (HttpURLConnection) url.openConnection();
...
...
..
int response=con.getResponseCode();
    }
}

uiThread如何知道networkThread中正在执行的int response的值?

一个简单的解决方案:创建某种回调,例如:

public interface Callback
{
    void done(int response);
}

将回调传递给您的 getUsers 方法。当您获得响应代码时,您可以调用 callback.done(response).

另一种方法是创建某种事件/侦听器,如@Jure mentionend。