2014-11-24 85 views
0

我正嘗試在當前正在運行的線程的運行方法中創建新線程。但新線程沒有開始,它阻止了當前正在運行的線程的執行。在JAVA中創建新線程時阻止運行方法

運行當前正在運行的線程的方法。

public void run() { 
     while(true){ 
      try{ 
       Message message = (Message)objIn.readObject(); 
       System.out.println("Received msg:"+message); 
       if(message.type.equals("connection")){ 
        if(message.content.equals("true")){ 
         System.out.println("connection successful"); 
         InetAddress senderIp = message.senderIp; 
         InetAddress receiverIp = message.receiverIp; 
         System.err.println(senderIp+"------"+receiverIp); 
         if(senderIp.getHostAddress().equals(receiverIp.getHostAddress())){ 
          //first member of ring topology 
          System.err.println("first member"); 
         }else{ 
          System.err.println("not the first member"); 
          ClientSideTempClient clientTemp = new ClientSideTempClient(receiverIp); 
          Thread obj1 = new Thread(clientTemp); 
          obj1.start(); 
          System.out.println("after starting local client tread..."); 
         } 
        }else{ 
         System.out.println("something went wrong"); 
        } 
       } 
      }catch(Exception e){ 
       System.out.println("Exception:"+e); 
      } 
     } 
} 

類新的線程: ClientSideTempClient.java

public class ClientSideTempClient implements Runnable{ 
    public Socket socket; 
    public ObjectInputStream objIn; 
    public ObjectOutputStream objOut; 
    public ClientSideTempClient(InetAddress serverIp){ 
     try{ 
      System.err.println("trying to connect"+serverIp.getHostAddress()); 
      String ipAddress = serverIp.getHostAddress(); 
      socket = new Socket(ipAddress, 9010); 
      objOut = new ObjectOutputStream(socket.getOutputStream()); 
      objOut.flush(); 
      objIn = new ObjectInputStream(socket.getInputStream()); 
     }catch(Exception e){ 
      System.err.println("Exception in ClientSideTempClient"+e); 
     } 

    } 
    public void sendMessageToLocalServer(Message msg){ 
     try { 
      objOut.writeObject(msg); 
      objOut.flush(); 
      System.out.println("Outgoing : "+msg.toString()); 
     }catch(Exception e){ 
      System.out.println("Exception in chatroom_client:"+e); 
     } 

    } 

    @Override 
    public void run() { 
     While(true){ 
      System.out.println("Execution started here"); 
     } 
    } 
} 

我搜索了這個的相關答案對谷歌的數字,但我沒有得到的IT解決方案。任何人都可以指導我解決這個問題?

+0

這是否編譯:'while(true){'?這是每一個打印:'System.out.println(「執行從這裏開始」);'? – 2014-11-24 01:10:31

+2

你確定它不是阻塞的構造函數嗎? – 2014-11-24 01:11:31

+0

@HovercraftFullOfEels:它不打印任何東西。 – Renaissance 2014-11-24 01:17:21

回答

0

您的ClientSideTempClient類在其構造函數中創建並連接Socket,這會延遲您的循環。 Socket和對象流應該在它自己的run()方法中創建,即在它自己的線程上。

注意你必須抓住EOFException,如果你得到它,就跳出這個循環。大多數其他IOExceptions也是致命的,除了SocketTimeoutException.

相關問題