多线程空指针异常java

时间:2017-02-19 20:40:33

标签: java multithreading nullpointerexception null-pointer

这个代码正常,我的意思是多线程部分.. 唯一的问题是,只有当我调用保存方法

时才能获得 NPE
  

线程中的异常" pool-1-thread-1"显示java.lang.NullPointerException           在app.Controller.handleClient(Controller.java:54)           在app.Controller.run(Controller.java:109)           at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)           at java.util.concurrent.ThreadPoolExecutor $ Worker.run(Unknown Source)           在java.lang.Thread.run(未知来源)

我该如何处理?谢谢

编码部分

BlockingQueue<Client> clients_list;

ExecutorService executor = Executors.newFixedThreadPool(10);

for (Client client: clients_list) {
        Runnable worker = new Controller(client);
        executor.execute(worker);
}

public Controller(Client client) {
        this.client = client;
}

// Controller类实现了Runnable,这里是run方法     @覆盖     public void run(){         //在客户端上做一些事情         //然后将数据保存到文件中         handleClient(客户端);     }

private void handleClient(Client client) {
    String c_rwx = client.getPermission()
    if(c_rwx.contains("allowed to:")) {
       client.setUsername = client.getUsername() + " allowed" ;
       save(client);
    }
}

private void save(Client client) {
        FileWriter fw = null;
        try {
            File file = new File("done.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file, true);
            fw.write("client info:" + client.getUsername() + " \n");
            // ...
            fw.flush();
        } catch (IOException ex) {
            System.out.println("err saving file");
        }
}

固定一切 在for

之后添加
executor.shutdown();

0 个答案:

没有答案