java - 从线程获取InputObjectStream

标签 java multithreading stream

我正在用 Java 制作一个聊天应用程序。

我有一个名为 Client 的类,其中有几种可以向我的服务器发送请求并等待响应的方法。 我曾经这样做过:

public  boolean  authenticate(String login, String password) throws ResponseException{
    try {
        AuthentificationRequest req = new AuthentificationRequest(login,password);
        this.out.writeObject(req);
        this.out.flush();

        Response rep=this.readResponse();

...

但我改变了从服务器接收响应的方式。现在我正在使用一个名为 ResponseHandler 的线程:

public void run() {
    // TODO Auto-generated method stub
    Response rep = new Response();
    try {       
        while (!Thread.currentThread().isInterrupted()) {
            this.isResponseReceived=false;
            this.setResponse((Response) in.readObject()) ;
            synchronized(this) {
                this.isResponseReceived=true;
                notify();   
            }

这是我的新方法“readResponse”:

public   Response readResponse(Request req) throws ClassNotFoundException, IOException, InterruptedException {
    synchronized(this.responseHandler) {

        while(!this.responseHandler.isResponseReceived()) {
            this.out.writeObject(req);      
            wait(); 
        }
    }
    this.out.flush();
    return this.responseHandler.getResponse();
}

这是我针对上一个示例的新客户端代码:

public  boolean  authenticate(String login, String password) throws ResponseException{
    try {

        Response rep = this.readResponse(new AuthentificationRequest(login,password));

但是看起来我的代码被阻塞到我的循环中...... 如何让我的客户端收到线程响应?

感谢您的反馈

最佳答案

我尝试让我的客户端通知并让我的 ResponseHandler 等待。我尝试了,但我的响应处理程序在等待模式下保持阻塞......

在我的客户端类中: 公共(public)响应 readResponse(Request req) 抛出 ClassNotFoundException、IOException、InterruptedException { 响应代表 = null;

    synchronized(this.in) {
        this.out.writeObject(req);  
        while(!this.responseHandler.isResponseReceived()) {
             rep = this.responseHandler.getResponse();
             in.notify();   
        }
    }
    this.out.flush();
    return rep;
}

在我的 ResponseHandler 类中运行方法:

synchronized(this.in){
                        wait();
                        this.isResponseReceived=true;
                        System.out.println("thread unlocked");
                    }

关于java - 从线程获取InputObjectStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53094016/

相关文章:

java - GregorianCalendar 给出了 "Asia/Singapore"时区的意外结果,系统日期为 2014 年 1 月 30 日

java - 在不使用 JNI 的情况下从 Java 调用 native 函数(使用堆栈操作)

C# 复杂线程同步

java - 使用外部模块中的包私有(private)构造函数实例化类

java - 在 C 中嵌入 Java 库

iphone - NSTimer在其他线程中不起作用

c# - 非阻塞线程

Flutter Dio 封装 : How to listen to download progress from another class?

stream - 如何制作长按按键时触发的KeyboardEvent流? ( Dart )

Python:tarfile 流