繁体   English   中英

在多线程环境中无法通过等待和通知从套接字输入流中读取

[英]Unable to read from the Socket Input Stream in a multithreaded environment with wait and notify

我正在使用2个线程-ReaderThread用于从Socket输入流读取,而WriterThread用于写入套接字输出流。 仅在写入流中而不从流中读取时,它们两个都可以正常工作。 但是,当我也在从输入流中读取时,程序不再运行,则挂起。

下面是执行WriterThread类中的代码。

try{
        Scanner consoleReader = new Scanner(System.in);
        String inst="";
        PrintWriter writer = new PrintWriter(client.getOutputStream(),true);
        while(true){
                synchronized(response){


                    System.out.print("Enter something: ");
                    System.out.flush();

                    inst=consoleReader.nextLine();
                    System.out.println(inst);
                    instruction.setInstruction(inst);
                    if(!instruction.getInstruction().equals("")){

                        writer.print(instruction.getInstruction());
                        writer.flush();
                        response.notifyAll();   

                        if(instruction.getInstruction().equalsIgnoreCase("end")){
                            break;
                        }
                        response.wait();

                    }
                }//End of response sync
        }//End of while
        }catch(IOException ioex){
            System.out.println("IO Exception caught in Writer Thread");
        }catch(InterruptedException iex){
            System.out.println("Writer thread interrupted");
        } 

上面的代码-从命令行读取,并使用“ writer”对象将其写入套接字输出流。

下面是从流中读取的代码-在ReaderThread类中

try{        
        Scanner reader = new Scanner(client.getInputStream());
        String txtRead="";
        outer:
        while(true){
            synchronized(response){
                response.wait();
                System.out.println("Reader Running");

                while(reader.hasNext()){ //Line-Beg
                    txtRead=reader.next();
                    System.out.println("Received: "+txtRead);
                    if(txtRead.equalsIgnoreCase("end")){
                        response.notifyAll();
                        break outer;
                    }
                }//End of reader while, Line-End

                response.notifyAll();
            }//End of response sync
        }//End of while
        }catch(IOException ioex){
            System.out.println("IOException caught in ReaderThread");
        }
        catch(InterruptedException iex){
                System.out.println("Interrupted ReaderThread");
        }  

上面的代码从Socket的输入流中读取数据。 上面的代码的问题是它在打印“ Reader Running”后无限期等待。 但是,当我注释掉从Line-Beg到Line-End的代码时,它会正确执行,从而为其他WriterThread写入输出流提供了机会。 为什么会这样呢?

注意:“响应”是用于同步的常见对象。 主方法完成执行后,还要关闭“服务器套接字”。 客户端套接字也是“ C”套接字。

我看不到使用notify()和wait()方法的问题。

reader.hasNext()在保持response对象锁定的同时阻塞,直到套接字输入流中的某些输入可用为止。 这样可以防止编写器线程获取response锁并写入套接字输出流。 为什么要在同一锁上同步读取器线程和写入器线程? 对我来说似乎没有必要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM