【问题标题】:Variable not change the valor in the thread变量不会改变线程中的值
【发布时间】:2015-06-17 07:51:12
【问题描述】:

我正在节点之间进行路由协议数据包,我认为以下问题与相关线程有关,这些线程正在覆盖变量,但不知道如何解决。我有错误如下的代码:

pclass nodosVecinos extends Thread {
public static int port = 0;
String num_Nodo = "";
byte[] buf = new byte[10000];
public synchronized void run() {
    DatagramPacket dP = new DatagramPacket(buf, buf.length);
    DatagramSocket sK = null;
    try {
        System.out.println(port);
        sK = new DatagramSocket(this.port);//<-- Problem
    } catch (SocketException e) {
        System.out.println("problem node "+num_Nodo);
        e.printStackTrace();
    }
    System.out.println("Node "+ num_Nodo +" up!"); // Nodo 1 encendido!
    while(true){
        try {
            sK.receive(dP);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Problem node , While");
        }
        System.out.println(buf.toString());

    }
}
public nodosVecinos (int puerto){
    port = puerto;
    num_Nodo = Integer.toString(port);
    num_Nodo = num_Nodo.substring(num_Nodo.length()-1,num_Nodo.length()); // 8001 => 1
}
public static void main(String args[]) {
}

}

我摆脱了断点:

8001 // <--- out in terminal
-1 // <--- Whit breackpoint and error.

我尝试将变量端口写入静态但不行。

感谢您的帮助。

编辑:

端口是同步的外部,是类变量。

【问题讨论】:

  • 端口变量如何设置?
  • port 是类的变量,所以基本上可以在你的同步方法之外进行设置和管理。
  • 我发布了完整的课程代码。

标签: java multithreading protocols network-protocols


【解决方案1】:

如何启动线程? 也许“同步”是问题所在。导致整个方法在新线程启动之前执行完毕,但是这个方法是无限的。

【讨论】:

  • 是的,这是永远的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
相关资源
最近更新 更多