简体   繁体   English

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

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

I'm trying to create a simple client/server app in java, it has a main that starts a thread - the listener thread and a runnable - the sender thread. 我试图用Java创建一个简单的客户端/服务器应用程序,它有一个主线程来启动一个线程-侦听器线程和一个可运行的-发送者线程。 They communicate with a working program. 他们与一个工作程序进行通信。 The socket is created on the Listener thread, as are the input and output static variables. 套接字在侦听器线程上创建,输入和输出静态变量也是如此。

The problem is : I can use the output, but only if I call it from the listener thread where it is defined. 问题是:我可以使用输出,但是仅当我从定义它的侦听器线程中调用它时才可以。 (output.writeBytes("0000");) When I try calling it from the Sender runnable, I get a null exception!! (output.writeBytes(“ 0000”);)当我尝试从Sender Runnable调用它时,出现空异常! (InfoListener.output.writeBytes("0000");) (InfoListener.output.writeBytes(“ 0000”);)

Here is my (not so smart) code, without all the exception handling : 这是我的代码(不是很聪明),没有所有异常处理:

* InfoListener.java file * * 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 file * * 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; 
        }
}

Please help :| 请帮助:|

In

while (InfoListener.can_start_sender = false)

you are assigning false to can_start_sender . 您将can_start_sender分配为false The while will therefore always resolve to false . 因此while将始终解析为false

It's possible that code following the while 这有可能下面的代码while

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

will get executed before the other Thread has time to initialize the static output field thus causing a NullPointerException . 将在另一个Thread有时间初始化static output字段之前执行,从而导致NullPointerException

Use 采用

while (!InfoListener.can_start_sender)

or better yet use a CountDownLatch or similar java.util.concurrent lock object. 或更好地使用CountDownLatch或类似的java.util.concurrent锁定对象。 You should also make can_start_sender volatile . 您还应该使can_start_sender volatile

暂无
暂无

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

相关问题 Java为什么会出现此错误? 线程“ main”中的异常java.lang.NullPointerException - Java Why do I get this error? Exception in thread “main” java.lang.NullPointerException 为什么在Java中读取简单文本文件时在do while循环中的if语句中出现NullPointerException - Why do i get a NullPointerException at If statement in do while loop when reading a simple textfile in Java 当我创建一个新类的实例时,为什么会出现java.lang.NullPointerException? - Why do I get a java.lang.NullPointerException when I make a new Instance of a my class? 尝试存储字节数组时,为什么会出现java.lang.NullPointerException? - Why do I get a java.lang.NullPointerException when I try to store a Array of Bytes? 通过RDP连接或更改分辨率时,为什么会出现java.lang.NullPointerException? - Why do I get java.lang.NullPointerException when I connect via RDP or change the resolution? 在Java中,使用多播套接字,我试图从另一台计算机获取输出,但是失败。 吗 - In Java, with Multicast Socket, I'm trying to get output from another computer, but fail. Wat do? 为什么会收到NullPointerException? - Why do I get a NullPointerException? 为什么会出现NullPointerException? - Why do I get NullPointerException? 为什么会收到此NullPointerException? - Why do I get this NullPointerException? 为什么在启动GUI时出现NullPointerException? - Why do I get a NullPointerException when I start my GUI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM