无法从run方法中访问对象的属性(方法)! Java多线程

时间:2016-02-15 05:00:48

标签: java multithreading udp

我在ServerConnectionManager中有以下代码:

public class ServerConnectionManager implements Runnable {

    private DatagramPacket receivedPacket;
    //some more things here


    public ServerConnectionManager(DatagramPacket receivedPacket){
        this.receivedPacket = receivedPacket;


        System.out.println("Connection manager has been assigned a request");
        System.out.println("The port of the request packet is "+receivedPacket.getPort());
         try {
             sendReceiveSocket = new DatagramSocket();
          } catch (SocketException se) {  
             se.printStackTrace();
             System.exit(1);
          }


    }

    @Override
    public void run() {

        //DEBUGGING LINES HERE
          System.out.println("The start method on connection manager works..");
          System.out.println("Point A");
          System.out.println("The port of the request packet is "+receivedPacket.getPort()); // the thread gets stuck here
          System.out.println("Does this work..?"); //This line never gets printed

          //some other stuff to be done here
                    }


         }

我在其他一些使用ServerConnectionManager的线程的run方法中有一些代码:让我们调用这个线程B

    @Override
    public void run() {

        while(true){
           try {        
                 System.out.println("Waiting..."); // so we know we're waiting
                 receiveSocket.receive(receivePacket);
              } catch (IOException e) {
                 System.out.print("Stopped Listening for some reason..");
                 //e.printStackTrace();
            }

            System.out.println("Server received something" );

           //Constructor of ServerConnectionManager
             ServerConnectionManager serverConnectionManager = new ServerConnectionManager(receivePacket);
             Thread managerThread = new Thread(serverConnectionManager, "connectionManager ");
             managerThread.start();

                 //some more stuff to be done

                }

        }

问题是我无法在ServerConnectionManager运行方法中调用receivedPacket上的任何方法。但是,我能够从此ServerConnectionManager线程的构造函数中调用receivedPacket.getPort(),它为我提供了预期的输出。但它在run方法中没有做任何事情。 ServerConnectionManager打印的最后一行是"点A"。之后什么都没有!!请查看我在该区域的调试评论,以便更好地了解我所说的内容。

我知道我提供了很多代码。但我根本无法理解这个问题。我已经尝试将其他参数(对象)从线程B传递给ServerConnectionManager的构造函数。我可以从ServerConnectionManager的run方法访问那些。它只是收到的袋子不起作用......

1 个答案:

答案 0 :(得分:1)

如果要启动新线程来处理它,则需要为每个接收创建一个新的DatagramPacket。否则,在receive()期间,一个线程在其上同步,而另一个线程正在尝试调用getPort()。在任何情况下,设计都是无效的,因为receive()将覆盖先前收到的数据报中的所有内容,同时线程正在尝试处理它。