2012-02-16 69 views
-2

我想使用連接來同步我的代碼。當調用連接時,我在父線程和子線程中都收到異常 線程運行時線程「thread3」異常 異常。Java當我打電話加入我在子和父線程中得到異常

線程運行在Ruinable類中,並在創建類時將線程存儲在公共成員中。主線程在這個公共成員上調用join方法。

碼主線程做

System.out.println(Thread.currentThread()+": waiting for 2 players"); 

do { 
    r=GetClient(); 
    switch(r) 
    { 
     case 0: return; // exitvon a very bad error 
    } 
} while(r==2);// loop if it was a timeout 
cMyConnection thread = new cMyConnection("thread3", connection, mPlayerList, mPlayersMessages); 
try { 
    thread.MyThread.join(); // call join 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} 

public class Cconnection implements Runnable { 
    Thread runner; 
    ReentrantReadWriteLock readWriteLock; 
    Lock read; 
    Lock write; 

    boolean StopFlag; 
    String header; 
    Socket connection; 
    ServerSocket server; 
    StringBuffer request; 
    OutputStream out; 
    InputStream in; 
    String ClientMessage; 
    public cUsers mPlayerList; 
    public cMessages mPlayersMessages; 
    public Thread MyThread; 

    public Cconnection(String threadName, Socket connection_in , cUsers PlayerList, cMessages PlayerMessages) { 
      connection=connection_in; 

      mPlayerList=PlayerList; 
      mPlayersMessages=PlayerMessages; 

      MyThread = new Thread(this, threadName); // (1) Create a new thread. 

      MyThread.start(); // (2) Start the thread. 
    } 
+0

修復帖子... – L7ColWinters 2012-02-16 02:19:10

+0

請包括stacktrace。 – mre 2012-02-16 02:46:04

回答

0

我是你爲什麼要使用線程,如果你啓動一個線程,然後立即等待它完成大問題?爲什麼不從你的主線調用cMyConnection.run()

此外,您的代碼在主要參考文獻cMyConnection,但您然後列出Cconnection。也許問題出在cMyConnection?它是什麼樣子的?

以下是關於你的問題補充幾句:

  • cMyConnection你的變量名可能不應該是thread。這很可能不是Thread類,這是什麼混淆@KL。也許connection是一個更好的名字?
  • 每當你在stackoverflow上提出一個問題時,你都應該用stack-trace中的相關行發佈異常。這總是有助於答覆者。
  • 我會考慮將start()join()方法添加到您的cMyConnection類。在一個類的構造函數中分支線程的想法有點不同尋常。至少你應該在javadocs中記錄它。
1

在你所說的「主線」創建線程,但不啓動它的片斷。你必須在調用thread.join()之前調用thread.start()。

乾杯,

+0

我有點困惑。 – 2012-02-16 13:49:32

+0

在這段代碼中:
'cMyConnection thread = new cMyConnection(「thread3」,connection,mPlayerList,mPlayersMessages); try { thread.MyThread.join(); //打電話加入 } catch(InterruptedException e){ e.printStackTrace(); }'
你缺少thread.start()
'cMyConnection線程=新cMyConnection( 「thread3」,連接,mPlayerList,mPlayersMessages);'** thread.start(); ** '嘗試{ thread.MyThread 。加入(); //打電話加入 } catch(InterruptedException e){ e.printStackTrace(); }' – klearn 2012-02-16 17:05:35

相關問題