2016-12-28 41 views
-1

所有我想要的是在同一時間我可以有多個方法在同一時間執行?

執行三種方法以上我說的不是帖子,因爲我已經嘗試線程,但它只是在一個時間

public void run() { 
    System.out.println("Running " + threadName); 
    try { 
    for(int i = 4; i > 0; i--) { 
     System.out.println("Thread: " + threadName + ", " + i); 
     // Let the thread sleep for a while. 
     Thread.sleep(50); 
    } 
    }catch (InterruptedException e) { 
    System.out.println("Thread " + threadName + " interrupted."); 
    } 
    System.out.println("Thread " + threadName + " exiting."); 

}

執行一個方法

在此代碼的一種方法會執行,然後睡大覺,等待另一個方法

的執行,但我想要的是讓三個方法執行在同一時間。

是否有可能?如果這是我該怎麼做,從哪裏開始?

+5

你的電腦有多少個CPU?如果只有一個,那麼它一次只能做一件事。否則「線索」實際上是對你的問題的正確答案。 –

+0

@DavidWallace - 即使在單核,單CPU的機器上,Java線程也可以很好地模擬多個同時執行的路徑。 –

+0

@TedHopp我同意。也許我正在從字面上解釋這個問題。 –

回答

3

您可能嘗試過線程,但聽起來好像你沒有正確地嘗試它們,如果每個方法都是單獨運行的。嘗試是這樣的:

public static void someMethod(int i) { 
    String me = Thread.currentThread().getName(); 
    Random r = new Random(); 
    while (i-- >= 0) { 
     System.out.println(me + ": i=" + i); 
     try { 
      // sleep some random time between 50 and 150 ms 
      Thread.sleep(r.nextInt(100) + 50); 
     } catch (InterruptedException e) { 
      System.out.println(me + " interrupted"); 
      return; 
     } 
    } 
    System.out.println(me + " exiting"); 
} 

public static void main(String[] args) { 
    int numThreads = 4; 
    for (int i = 0; i < numThreads; ++i) { 
     new Thread("Thread " + i) { 
      @Override public void run() { someMethod(10); } 
     }.start(); 
    } 
} 

你會看到從someMethod輸出混合在一起的所有線程。每次運行代碼時都應該有所不同。

相關問題