2016-12-28 43 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输出混合在一起的所有线程。每次运行代码时都应该有所不同。

相关问题