【问题标题】:Java asynchronous text input and outputJava异步文本输入输出
【发布时间】:2015-01-06 00:17:57
【问题描述】:

我必须说我是 Java 的初学者。 我使用 Eclipse。我想完成以下场景,但找不到怎么做:

当 java 程序运行时,它会向控制台输出文本,我还希望能够输入文本并处理它,而不会因等待输入而阻塞输出。

假设:

-线程1每秒向控制台输出一个数字

-线程 2 监听输入

(代码是样机)

//**Thread 1:**

int incrementBy = 0;

for (int i = 0; i < 1000; i++) {

    i = i + incrementBy;

    //Pause for 1 seconds
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        System.out.println("TEXT OUTPUT INTERUPTED");
    }
    //Print text
    System.out.println(i);
}



//**Thread 2:**
String myIncrement = System.console().readLine();

(Now process the input and change the incrementBy var in Thread 1)

现在在我的程序中,我使用 1 个线程进行输入,另一个线程用于输出。但我可以很容易地改变设计。 我能找到的只是关于服务器和客户端的东西,我想把我的代码放在一个地方包中。而且我目前不知道如何制作一个带有一个用于输出和一个用于输入的文本框的 GUI。

你能推荐一些吗?

【问题讨论】:

    标签: java asynchronous io


    【解决方案1】:

    已解决 - 事实证明我对 JAVA 非常陌生。

    似乎java允许用户输入文本,而另一个线程输出到控制台。

    这就是为什么我在搜索“java 输入和输出到控制台异步”之类的内容时找不到任何内容的原因。我的输入代码中有一个问题,正是我要求输入的地方,因为我从单线程程序中知道程序会暂停,直到我输入文本并按下回车键,我认为抛出错误是因为输出线程正在接管控制台并终止输入线程。

    这是我的代码供那些搜索的人使用(以它为指导,如果编译可能不起作用):

    //Main app
    public class textInpuOutputManager {
    
      //here we create the two threads (objects that implement the runnable interface)
      static TextInputObject ti;
      static TextOutputObject to;
    
      public static void main(String[] args) {
        //we instantiate the objects
        ti = new TextInputObject();
        to = new TextOutputObject();
        //we call the start method to start the threads for input and output
        ti.start();
        to.start();
      }
    
    }
    
    
    //TextInputObject class
    public class TextInputObject implements Runnable {
    
      //Method that gets called when the object is instantiated
      public TextInputObject() {
        System.out.println("Created TextInputObject");
      }
    
      //create a thread object and check if it's not already created
      static Thread thread;
    
      //This method gets called from the main
      public void start() {
        if (thread == null) {
          thread = new Thread(this);
          thread.start();
        }
      }
    
      //this method gets called by the thread.start(); from above
      @
      Override
      public void run() {
        System.out.println("Text input thread created and now it runs");
    
        readTextFromConsole();
      }
    
      Scanner inputReader = new Scanner(System.in);
    
      //check for input all the time - THIS WILL NOT HALT THE PROGRAM
      public void readTextFromConsole() {
        System.out.println("Enter something:");
        String myinput = inputReader.nextLine();
        System.out.println("You Entered: " + myinput);
        readTextFromConsole();
      }
    
    }
    
    
    //TextOutputObject
    public class TextOutputObject implements Runnable {
    
      //Method that gets called when the object is instantiated
      public TextOutputObject() {
        System.out.println("Created TextOutputObject");
      }
    
      static Thread thread;
    
      public void start() {
        if (thread == null) {
          thread = new Thread(this);
          thread.start();
        }
      }
    
      @
      Override
      public void run() {
        System.out.println("Text output thread created and now it runs");
    
        //Make it output text every 4 seconds to test if you can input text while it's used for output
        for (int i = 0; i < 100; i++) {
          //Pause for 4 seconds
          try {
            Thread.sleep(4000);
          } catch (InterruptedException e) {
            System.out.println("TEXT OUTPUT INTERUPTED");
          }
          //Print i to console
          System.out.println(i);
        }
      }
    
    }

    也非常感谢所有花时间回复的人

    【讨论】:

      【解决方案2】:

      您可以创建两个内部类并在它们中实现 Runnable。

      import java.util.Scanner;
      
      public class Test{
      
      private Thread t1;
      private Thread t2;    
      
      public static void main(String[] args){
          new Test();
      }
      
      private class TOne implements Runnable{
          public void run(){
              int incrementBy = 0;
      
              for (int i = 0; i < 1000; i++) {
      
                  i = i + incrementBy;
      
                  //Pause for 1 seconds
                  try {
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      System.out.println("TEXT OUTPUT INTERUPTED");
                  }
                  //Print text
                  System.out.println(i);
              }
          }
      }
      
      private class TTwo implements Runnable{
          public void run(){//Code for Thread 2
              try{
                  Scanner scr = new Scanner(System.in);
                  System.out.println(scr.next());
              }catch(Exception ex){
                  ex.printStackTrace();
              }
          }
      }
      public Test(){
          t1 = new Thread(new TOne());
          t1.run();
          t2 = new Thread(new TTwo());
          t2.run();
      }
      }
      

      不是最优雅的方式,也不是完美无缺的。您必须对第二个线程进行更多修改。有关 GUI 等如何工作的信息,您应该查看 Swing 库。谷歌搜索它应该可以正常工作。

      对您来说一些重要的关键字是: JFrame、JPanel、LayoutManager、JTextArea、JTextField、JButton、ActionListener、内部类

      【讨论】:

      • 谢谢user3046986,您的回答与我的方法几乎相同,我的问题是错误编码引发的异常,正是我要求输入的地方,并且由于我过去的经验,我得出的结论是控制台不允许。您的回答使我更好地查看了我的代码。也感谢您提供的关键字,我一定会检查出来。
      【解决方案3】:

      我不确定您到底想做什么,但如果您是新手并且不知道如何制作 gui,我会尝试 JOptionPane

       String input = JOptionPane.showInputDialog("User input is returned as a string; use Integer.parseInt(input) to retrieve an integer from this method");
      

      【讨论】:

        猜你喜欢
        • 2011-12-07
        • 2013-05-04
        • 2021-07-15
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多