2012-02-23 45 views
0

我在java中的线程有点麻烦。基本上我创建一个线程数组并启动它们。该计划的重点是模拟比赛,为每个参赛者(即每个线程)总计时间并挑选获胜者。线程的一些问题

竞争对手移动一个空间,等待(即线程睡眠5到6秒之间的随机时间段),然后继续。线程没有按照预期的顺序完成。

现在的问题。我可以得到一个线程完成所需的总时间;我想要的是将线程中的所有时间存储到一个数组中,并能够计算最快的时间。

要做到这一点,我应该把数组放在main.class文件中?我是否会正确地承认,因为如果它被放置在Thread类中,它将无法工作。或者我应该创建第三堂课吗?

我小有一点困惑:/

回答

4

它的优良声明它在你调用线程的方法,有几点注意事项:

  • 每个线程都应该知道其在数组中的索引。也许你应该通过这个在构造
  • 那么你有三种选择填充阵列
    • 阵列应该是final,以便它可以匿名类
    • 数组可以传递给每个线程
    • 内使用
    • 线程应该在完成时通知监听器,这反过来会增加一个数组。
  • 考虑使用Java 1.5 Executors framework来提交Runnables,而不是直接使用线程。
+0

我会建议使用'ConcurrentHashMap'代替阵列 – yegor256 2012-02-23 23:03:49

+0

是,也能发挥作用,而不是线程应该知道自己的指数。 – Bozho 2012-02-23 23:05:12

+0

感谢所有的答复 - 我正在努力实现它现在。 BTW考虑共享变量是否涉及我可以使用关键字易失性?或者这是矫枉过正,因为线程将写入数组中的不同位置? – Katana24 2012-02-25 13:47:02

2

编辑:下面的解决方案假设你只需要所有的竞争对手已经完成比赛。

您可以使用如下所示的结构(在您的主类中)。通常你想添加很多你自己的东西;这是主要提纲。

请注意,并发并不是一个问题,因为在线程运行完毕后,您会从MyRunnable实例中获取值。

请注意,对于每个竞争对手使用单独的线程可能不是真正需要修改的方法,但这将是一个不同的问题。

public static void main(String[] args) { 
    MyRunnable[] runnables = new MyRunnable[NUM_THREADS]; 
    Thread[] threads = new Thread[NUM_THREADS]; 

    for (int i = 0; i < NUM_THREADS; i++) { 
     runnables[i] = new MyRunnable(); 
     threads[i] = new Thread(runnables[i]); 
    } 

    // start threads 
    for (Thread thread : threads) { 
     thread.start(); 
    } 

    // wait for threads 
    for (Thread thread : threads) { 
     try { 
      thread.join(); 
     } catch (InterruptedException e) { 
      // ignored 
     } 
    } 

    // get the times you calculated for each thread 
    for (int i = 0; i < NUM_THREADS; i++) { 
     int timeSpent = runnables[i].getTimeSpent(); 
     // do something with the time spent 
    } 
} 

static class MyRunnable implements Runnable { 
    private int timeSpent;   

    public MyRunnable(...) { 
     // initialize 
    } 

    public void run() { 
     // whatever the thread should do 

     // finally set the time 
     timeSpent = ...; 
    } 

    public int getTimeSpent() { 
     return timeSpent; 
    } 
}