0

我正在尝试在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; 
        }
}

请帮助:|

4

1 回答 1

1

while (InfoListener.can_start_sender = false)

你分配falsecan_start_sender. 意志因此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.

于 2013-09-26T04:08:43.257 回答