繁体   English   中英

为什么在写入另一个线程上定义的套接字输出时得到(java)NullPointerException?

[英]Why do I get a (java) NullPointerException when writing to a socket's output, defined on another thread?

我试图用Java创建一个简单的客户端/服务器应用程序,它有一个主线程来启动一个线程-侦听器线程和一个可运行的-发送者线程。 他们与一个工作程序进行通信。 套接字在侦听器线程上创建,输入和输出静态变量也是如此。

问题是:我可以使用输出,但是仅当我从定义它的侦听器线程中调用它时才可以。 (output.writeBytes(“ 0000”);)当我尝试从Sender Runnable调用它时,出现空异常! (InfoListener.output.writeBytes(“ 0000”);)

这是我的代码(不是很聪明),没有所有异常处理:

* InfoListener.java文件*

public class InfoListener extends Thread {

    public int port = 5000;
    public Socket socket = null;
    static BufferedReader input;
    static DataOutputStream output;
    static boolean can_start_sender = false;

    static boolean active = true;
    static String answer="";

    public void run() 
    {               
        // init socket
        socket = new Socket("127.0.0.1", port);
        output = new DataOutputStream(socket.getOutputStream());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        can_start_sender = true;

        while (active) // while main app is active
        {
            // Read new data!!
            answer = input.readLine();
            if (answer!=null)
            {
                System.out.println("Info : Listener received : " + answer);
            }
        }
    }
}

* InfoSender.java文件*

public class InfoSender implements Runnable {


    static InfoListener infoListener;
    static InfoSender infoSender;
    static String string_to_send = "0000";

    public static void main(String[] args)
    {
        // start listener
        infoListener = new InfoListener();
        infoListener.start();

        // Start Sender
        infoSender = new InfoSender();
        infoSender.run();

        while (infoListener.isAlive())
            Thread.sleep(100);
    }

    public void run()
    {
        //attempt to connect to the server and send string
        // Wait for socket
        while (InfoListener.can_start_sender = false)
            Thread.sleep(100);

        // write -------- HERE IS THE NULLPOINTEREXCEPTION ------------
        InfoListener.output.writeBytes(string_to_send);
        System.out.println("Info : info sent :"+ string_to_send);

        // wait a bit for listener to get response back, then close
        Thread.sleep(10000);
        InfoListener.active = false; 
        }
}

请帮助:|

while (InfoListener.can_start_sender = false)

您将can_start_sender分配为false 因此while将始终解析为false

这有可能下面的代码while

// write -------- HERE IS THE NULLPOINTEREXCEPTION ------------
InfoListener.output.writeBytes(string_to_send);

将在另一个Thread有时间初始化static output字段之前执行,从而导致NullPointerException

采用

while (!InfoListener.can_start_sender)

或更好地使用CountDownLatch或类似的java.util.concurrent锁定对象。 您还应该使can_start_sender volatile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM