[英]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.