在跨线程“ Thread-0”中获取Exception的同时发送数据时,java.lang.NullPointerException

时间:2019-07-10 08:20:33

标签: java multithreading nullpointerexception

我是多线程的新手,但是,我已经阅读了类似问题的答案,但无法理解。下面的代码抛出NullPointerException,我已经启动了Data对象(我认为是),但是我收到了错误。

"Exception in thread "Thread-0" java.lang.NullPointerException
    at Concepts.Sender.run(UnderstandingSendRceiveThreads.java:87)
    at java.base/java.lang.Thread.run(Thread.java:834)"

预先感谢您的帮助。

我尝试手动初始化d.data(使用构造函数和不使用构造函数),并且还进行了代码更改以附加值,即this.data = in + data。 但是没用。

package Concepts;

public class UnderstandingSendRceiveThreads {

    public static void main(String... args) {
    Data d = new Data();
    Sender ob1 = new Sender(d);
    Receiver ob2 = new Receiver(d);
    ob1.t.start();
    ob2.t.start();
        try {
            ob1.t.join();
            ob2.t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Data {
    private  boolean isSender = true;
    private String data  ;

   synchronized void sender(String in){
        while (!isSender){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
       System.out.println(in);
       System.out.println(this.data);
        this.data=in;
       isSender = false;
        notify();
    }

    synchronized String receive(){

       while (isSender){

           try {
               wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
        isSender= true;
        notify();
        return data;

    }
}

class Sender implements Runnable {

    Thread t;
    Data d;

    Sender(Data d){
        t=new Thread(this);
        d= this.d;

    }

    public void run(){
        String[] sendData = {"TV", "Fridge", "Randomthings", "END"};

        for(String data: sendData){
            d.sender(data);
        }
    }
}

class Receiver implements Runnable{
    Thread t;
    Data d;
    Receiver(Data d){
        t = new Thread(this);
        this.d = d;
    }

    public void run(){

        for(String receivedData = d.receive(); !"END".equals(receivedData);receivedData=d.receive()){
            System.out.println(receivedData);
        }
    }
}

Data类应使用sender函数接受值并将其存储在data(字符串变量)中。

1 个答案:

答案 0 :(得分:1)

看看您的Sender构造函数:

Sender(Data d){
    t = new Thread(this);
    d = this.d;
}

您要为参数 d分配字段 this.d的值。您应该将以下语句翻转:

this.d = d;

假设您没有将null传递给构造函数,则应停止在NullPointerException方法中获得Sender#run