【问题标题】:I'm trying to run console input in a thread in Java but my program is getting hungup on the readLine() method我正在尝试在 Java 的线程中运行控制台输入,但我的程序在 readLine() 方法上挂起
【发布时间】:2015-07-19 22:28:33
【问题描述】:

我正在创建这个程序来测试在聊天服务器程序的线程中获取用户输入。该程序在read = into.readLine(); 停止。为什么会这样?发生了什么?

代码如下:

    import java.io.*;
    import java.net.*;

    public class ThreadClass implements Runnable
    {
        DataInputStream in;
        private boolean checkLoop = false;


    public void run()
    {
        BufferedReader into = new BufferedReader(new        InputStreamReader(System.in));
        String read;
        System.out.println("Welcome...");
        while(!checkLoop)
        {
            try
            {
                System.out.println("running1");
                read = into.readLine();
                System.out.println(read);
                if(read.equals(".bye"))
                {
                    checkLoop = true;
                }
                Thread.sleep(500);
            }
            catch(IOException e)
            {
                System.out.println(e);System.out.println("running2");
            }
            catch (InterruptedException ie)
            {
                System.out.println(ie);System.out.println("running3");
            }
        }
        System.out.println("running4");
    }

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

    }

【问题讨论】:

  • 修改 if 条件 : if(read.equals(".bye")) 为 if(read.equals("bye")) 为什么 .bye 同时比较??
  • @user403348255 不能解决 readLine() 的问题...可能是错字。
  • 您在控制台中输入了什么吗?
  • 您是否正在输入任何内容供 readLine 读取?它需要数据来读取......
  • 控制台不允许我输入任何内容。如果我在没有线程的情况下单独运行这个程序,那么它工作正常。

标签: java multithreading bufferedreader system.in


【解决方案1】:

当你使用“read = into.readLine();”程序将停止并等待用户按下“Enter”键。从我的角度来看,您的程序运行良好。

尝试在控制台输入一些东西,你会看到程序运行正常。

【讨论】:

    猜你喜欢
    • 2012-10-21
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多