Java,当我调用join时,我在子线程和父线程中获得异常

时间:2012-02-16 02:07:45

标签: java multithreading

我正在尝试使用join来同步我的代码。当调用join时,我在父线程和子线程中都会遇到异常 线程“thread3”中的异常 线程运行中的异常。

线程在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.
    }

2 个答案:

答案 0 :(得分:1)

在你称为“主线程”的代码片段中,您创建了线程,但是没有启动它。你必须在调用thread.join()之前调用thread.start()。

干杯,

答案 1 :(得分:0)

我的一个大问题是,如果你正在启动一个线程然后立即等待它完成,你为什么要使用线程?为什么不从主线程中调用cMyConnection.run()

此外,您的代码在主要参考cMyConnection中,但随后列出Cconnection。问题可能在cMyConnection?它看起来像什么?

以下是关于您的问题的一些其他评论:

  • cMyConnection的变量名称可能不是thread。它很可能不是Thread类,它使@KL感到困惑。也许connection是一个更好的名字?
  • 每当您在stackoverflow上询问问题时,都应该使用堆栈跟踪中的相关行发布异常。这总能帮助回答者。
  • 我会考虑将start()join()方法添加到您的cMyConnection课程中。在一个类的构造函数中它分叉一个线程的想法有点不寻常。至少你应该在javadocs中记录它。