2016-04-08 170 views
1

我已經寫了一些簡單的代碼來顯示一個不斷從一邊移動到另一邊的加載詞。是否有可能打印另一個字符串,而前一個打印?如何在另一個打印時打印字符串?

它看起來是這樣的:

..loading(這個詞不斷移動)
加載主文件。
加載備份文件。
....(這些線得到僅輸出一次,而在裝載仍在移動)

我要爲下一個行的代碼以與裝載代碼分開。

加載三字代碼:

public static void main(String[] args) throws Exception 
    { 
     for (int i=0; i<86; i++) 
     { 
      if (i%17 == 0) 
       System.out.print(".......... \r"); 
      if (i%17 == 1) 
       System.out.print(".........L \r"); 
      if (i%17 == 2) 
       System.out.print("........Lo \r"); 
      if (i%17 == 3) 
       System.out.print(".......Loa \r"); 
      if (i%17 == 4) 
       System.out.print("......Load \r"); 
      if (i%17 == 5) 
       System.out.print(".....Laodi \r"); 
      if (i%17 == 6) 
       System.out.print("....Loadin \r"); 
      if (i%17 == 7) 
       System.out.print("...Loading \r"); 
      if (i%17 == 8) 
       System.out.print("..Loading. \r"); 
      if (i%17 == 9) 
       System.out.print(".Loading.. \r"); 
      if (i%17 == 10) 
       System.out.print("Loading... \r"); 
      if (i%17 == 11) 
       System.out.print("oading.... \r"); 
      if (i%17 == 12) 
       System.out.print("ading..... \r"); 
      if (i%17 == 13) 
       System.out.print("ding...... \r"); 
      if (i%17 == 14) 
       System.out.print("ing....... \r"); 
      if (i%17 == 15) 
       System.out.print("ng........ \r"); 
      if (i%17 == 16) 
       System.out.print("g......... \r"); 


      Thread.sleep(150); 
     } 

    } 
+0

我在Windows命令提示符下運行代碼。 – farshad

回答

1

亞當triying對你說,你必須使用一個線程。

線程是java中的一個進程,代碼在主線程處理器中執行,但是您可以創建另一個線程同時執行另一件事情,在計算機信息中稱此類事情稱爲併發。

,我建議你學習的東西更多關於Java線程,也許這可以幫助你:http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html

對於另一端,你可以在條件到底放的System.out.println把另一個字符串。

1

你必須這樣做在一個單獨的Thread。不幸的是,你必須確保在print期間你的兩個線程不會有上下文切換。假設您要打印文字loadingCOUNTING。然後,在沒有任何同步的情況下,打印的消息很可能是這樣的:loCOUaNTdiINGing

請在Java中這裏瞭解併發:http://tutorials.jenkov.com/java-concurrency/index.html

+0

你能解釋一下嗎? – farshad

+1

@farshad您需要執行多個線程才能同時打印多個內容,並確保它們已同步。這意味着線程2需要知道線程1正在打印哪些字符,以避免重複(等等)。除了Adam提供的美麗鏈接之外,[這是另一個](http://www.tutorialspoint.com/java/java_multithreading.htm),您可能會感興趣。 –

+0

現在我明白它是如何工作的,但對於像我這樣的初學者來說,使用它看起來像是一件進步的事情,但我一定會嘗試瞭解更多。可以進來真的很方便。 – farshad