Java 用于与UI线程通信的网络线程
我已经为Java应用程序中的多线程创建了一个类 导入java.util.concurrent.Executor; 导入java.util.concurrent.Executors 公共类应用线程{Java 用于与UI线程通信的网络线程,java,java-threads,Java,Java Threads,我已经为Java应用程序中的多线程创建了一个类 导入java.util.concurrent.Executor; 导入java.util.concurrent.Executors 公共类应用线程{ private static final Object LOCK = new Object(); private static AppThreads sInstance; private final Executor diskThread; private final Executor uiThrea
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-indicationend。创建事件和监听器?java中的事件和监听器示例有链接吗?