网络线程以与UI线程进行通信

时间:2018-09-21 06:07:19

标签: java java-threads

我已经为Java应用程序中的多线程创建了一个类。

import java.util.concurrent.Executor; 导入java.util.concurrent.Executors;

公共类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将如何知道int response中正在执行的networkThread的值?

1 个答案:

答案 0 :(得分:1)

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

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

将回调传递给您的getUsers方法。收到响应代码后,您就可以致电callback.done(response)

一种替代方法是创建某种事件/侦听器,如@Jure sayend。