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

我在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的run方法中调用ReceivedPacket上的任何方法。但是,我能够从此ServerConnectionManager线程的构造函数中调用receivedPacket.getPort(),它给了我预期的输出。但是它在run方法中没有任何作用。ServerConnectionManager打印的最后一行是“

Point A”。之后没有!!请检查我在该区域的DEBUGGING评论,以更好地了解我在说什么。

我知道我提供了很多代码。但是我根本无法理解问题。我尝试将其他参数(对象)从线程B传递到ServerConnectionManager的构造函数。而且我能够通过ServerConnectionManager的run方法访问它们。它只是receivedPacket不起作用…

回答:

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

以上是 无法从run方法中访问对象的属性(方法)!Java多线程 的全部内容, 来源链接: utcz.com/qa/403693.html

回到顶部