2014-11-09 3 views
1

나는 자바 초보자 다. Eclipse를 사용합니다. 다음 시나리오를 수행하고이를 수행하는 방법을 찾을 수 없습니다.자바 비동기 텍스트 입출력

Java 프로그램을 실행하는 동안 콘솔에 텍스트를 출력하는 동안 텍스트를 입력하고 출력을 차단하지 않고 처리 할 수 ​​있기를 원합니다. 입력을 기다리고있다.

이 가정 :

-thread 1 입력 콘솔 매초

-thread 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를 만드는 방법을 모른다.

뭔가 추천 할 수 있습니까?

답변

2

이 해결 - 그것은 내가 아주 아주 새로운 자바에 대한 생각 밝혀졌습니다.

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); 
 
    } 
 
    } 
 

 
}
또한

BIG이 걸렸다 여러분 모두 감사드립니다 응답 할 시간

0

나는 당신이 원하는 정확히 그것이 잘 모르겠지만, 당신이 새로운이야 그리고 당신은 GUI를 만드는 방법을 모른다면, 나는 JOptionPane에이

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

당신이 만들 수있는 시도 할 것이다 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 라이브러리를 확인하십시오. 그것은 정상적으로 작동합니다 인터넷 검색. 당신이 할 수 wpuld에 대한

몇 가지 중요한 키워드 : JFrame의, JPanel에, LayoutManager에, JTextArea에, JTextField를,하는 JButton, ActionListener를, 내부 클래스

+0

감사합니다. user3046986, 당신의 대답은 제 접근법과 거의 같습니다, 제 문제는 입력 코딩을 요구하는 곳에서의 잘못된 코딩이었습니다. 과거의 경험으로 인해 제가 콘솔로 넘어갔습니다. 암사슴 그것을 허용하지 마십시오. 귀하의 답변으로 제 코드를 더 잘 살펴볼 수있었습니다. 또한 키워드에 대해 감사 드리며, 나는 그들을 확인해 보겠습니다. –