我在运行java Threads时遇到麻烦,它只会运行一次

时间:2014-05-29 08:14:03

标签: 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){}
    }

我得到的输出是 SSS 就一次。但我有一个永远是真的循环。为什么不能无限地运行?

3 个答案:

答案 0 :(得分:1)

(由于声誉不佳而无法发表评论......)

以这种方式更好地阅读:

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

PS:小心,你打电话2次readLine()

答案 1 :(得分:1)

您需要做的是删除catch和IOException

如果你不止一次需要这样的线程,你应该考虑将它封装在一个类中。

在这里看到:

public class Foo extends Thread
{
    public Foo()
    {
        super("Foo");
    }

    @Override
    public void run()
    {

        while(!isInterrupted())
        {
            System.out.println("Still running");

            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) 
    {
        Thread foo = new Foo();
        foo.start();
    }
}

否则,您可以考虑实现Runnable接口,因为它被认为是使用Java中的Threads处理的首选方式。

如需了解更多信息,请查看:

"implements Runnable" vs. "extends Thread"

希望这有帮助。

答案 2 :(得分:0)

你调用readLine两次,在每个调用中它都会获取下一行,所以第一行是读取行,第二行没有任何内容可读,所以它卡住了