无法在Thread的构造函数中初始化PrintWriter字段

时间:2012-06-02 23:43:24

标签: java

需要为每个连接创建一个新线程。线程应具有写入套接字的功能,即使它在run()中等待客户端输入:String clientCommand = in.readLine()。函数update应满足此要求,并且能够使用PrintWriter outWr写入套接字,但它似乎是null,即使在线程构造函数中设置它也是如此。 无法在构造函数中初始化PrintWriter outWrtry构建后outWr仍然是null。如何解决?


public class Server {
    public static void main(String[] args) { 
        ...
        ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++, auction);
        ...
}

public class ClientServiceThread extends Thread  {
private PrintWriter outWr;

ClientServiceThread(Socket s, int clientID, Auction a) {
        try {
            PrintWriter outWr = new PrintWriter(new OutputStreamWriter(
                    m_clientSocket.getOutputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public void run() {....; String clientCommand = in.readLine(); ... }
public void update(String msg){outWr.println(msg);}

1 个答案:

答案 0 :(得分:4)

看看这段代码

public class ClientServiceThread extends Thread  {
private PrintWriter outWr;

ClientServiceThread(Socket s, int clientID, Auction a) {
        try {
            PrintWriter outWr = new PrintWriter(new OutputStreamWriter(

在构造函数中,您不初始化类字段,而是初始化本地引用PrintWriter outWr

将其更改为

        try {
            outWr = new PrintWriter(new OutputStreamWriter(