我对数据报套接字和线程都是新手。当我在命令提示符下运行代码时,我期望看到6500和6501都可以打印出来,但只能看到6500。为什么代码没有运行第二个start()?如何对多个接收数据报套接字进行线程化(最简单的方法,不一定是最好的方法)?

public class startThread {
public static void main(String[] args) throws Exception, IOException {
    new routerInterface(6500, "receive").start();
    new routerInterface(6501, "receive").start();
}
}

public routerInterface(int virPort, String action) throws Exception{
    System.out.println(virPort);
    if (action.compareTo("receive")==0){
        request = new DatagramSocket(clientPort);
        receive();
    }
}

public static void receive() throws Exception{
      while(true) {
          System.out.println("We are recieving here");
          DatagramPacket p = new DatagramPacket(udpPack, udpPack.length);
          request.receive(p);
          byte[] reciv = p.getData();
      }
}

最佳答案

您需要从receive()方法而不是从构造函数调用run()

10-07 17:09