Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用于与UI线程通信的网络线程_Java_Java Threads - Fatal编程技术网

Java 用于与UI线程通信的网络线程

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

我已经为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 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中的事件和监听器示例有链接吗?