java - 我在运行 java 线程时遇到问题,它只能运行一次

标签 java multithreading sockets try-catch

我正在使用套接字设计一个聊天应用程序。这是从服务器读取数据的代码。 它编译得很好,但线程只运行一次。请帮帮我。

public void reader() {
    Thread read=new Thread(){
        public void run(){
            try {
                while(true) {
                    if(in.readLine()!=null) {
                        System.out.println("Recived Message: "+ in.readLine());
                    }
                }
            }catch(Exception e){}
        }
    };

    read.setPriority(10);
    read.start();
} 

好吧,我尝试了这段代码,但它不起作用

public void reader()
{
    Thread u=new Thread()
        {
        public void run()
            {
            try {
            while(true)
            {
                System.out.println("ssss");
                if(input.readLine()!=null)
                {
                    String message=input.readLine();
                    System.out.println("SERVER:"+message);
                }
                else{
                    Thread.sleep(1);
                }

            } 
            }
            catch (IOException e)

                e.printStackTrace();
            } catch (InterruptedException e) 
            {
                e.printStackTrace();
            }

            }

    };
    try{
    u.start();
    }catch(Exception e){}
    }

我得到的输出是 SS 就一次。但我有一个 while 循环始终为真。为什么 ir 不无限运行?

最佳答案

(由于信誉低而无法发表评论...)

这样更好地阅读行:

String line = "";
while( (line = in.readLine()) != null) {
    System.out.println("Recived Message: " + line);
}

PS:小心,您正在调用 2 次 readLine()

关于java - 我在运行 java 线程时遇到问题,它只能运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23928745/

相关文章:

java - 如何在 REST Web 服务中进行身份验证?

java - Jersey 2.27 无法处理 POST

c# - 如何优雅地访问线程安全集合并使用 AutoResetEvent

在 C 中清除 char 数组

java - Android-Firebase-为每个用户创建一个数据文件

java - 二进制信号量的使用 - 无法正常工作(卖票)

c++ - boost 互斥量和类成员访问

java - 是否可以使用多个 java ObjectOutputStream 对象写入单个 java ObjectInputStream 对象?

python 立即发送 TCP/IP 数据

java get属性只存在于子类中