2016-09-28 41 views
0

實際上我使用線程同時打印兩個名字,並且我想在按'e'字母后停止執行。 但我不想按'e'然後按Enter鍵。我只想按字母'e'來停止。停止在控制檯應用程序中按下字母'e'的java程序

import java.io.*; 
class multithreads{ 
    public static void main(String[] args) { 


     thread4 t1=new thread4("firstname",500,500); 

     thread4 t2=new thread4("Secondname",1000,0); 

     thread4 t3=new thread4("exit",10,0); 


     } 
} 

類thread4實現Runnable {

static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); 
Thread t; 
String name; 
int msg='c'; 
static boolean over=true; 
int t1; 
int t2; 
thread4(String s,int a,int b){ 
    name=s; 
    t1=a; 
    t2=b; 
    t=new Thread(this,s); 
    t.start(); 

} 

public void run(){ 




    while(over){ 

    if(name.equals("exit")){ 


     try{ 
      msg=in.read(); 
      try{ 
      t.sleep(t1); 

     } 
     catch(InterruptedException e){ 
      System.out.println(e); 
     } 



     }catch(Exception eio){ 
      System.out.println(eio); 
     } 

     if(msg=='E'){ 
      over=false; 
     }else{ 
      msg='c'; 
     } 


    }else{ 



     try{ 
      t.sleep(t1); 

     } 
     catch(InterruptedException e){ 
      System.out.println(e); 
     } 

     System.out.print(name); 
     for(int j=name.length();j>0;j--){ 


     System.out.print("\b\b\b"); 
     } 
     try{ 
      t.sleep(t2); 

     } 
     catch(InterruptedException e){ 
      System.out.println(e); 
     } 
     } 


     } 

    } 
} 
+1

歡迎來到Stack Overflow!爲了幫助您充分利用本網站,請花點時間閱讀我們的[SO問題清單](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)並重新修正您的問題因此。 –

+0

可能的重複:http://stackoverflow.com/questions/17555515/how-to-get-input-without-pressing-enter-every-time –

回答

1

沒有這樣的可能性。我們無法在控制檯中添加諸如按鍵監聽器之類的東西 - 這不是我們的計劃。輸入數據的唯一方法是輸入Enter

+0

是的,我認爲是。我認爲這是可能的在C. –