线程背后的逻辑

时间:2012-03-05 10:32:28

标签: java

我通过以下方式模拟了比赛:

// starts the timer + betting iterations
public void run() {

    for (int i = 25; i >= 0; i--) {
        try {
            Thread.sleep(1000);
            h.setTime(Integer.toString(i)); //h.setLblTime1(Integer.toString(i)); 

        } catch (InterruptedException ex) {
            Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Thread t0 = new Thread(new runHorses(h, 0)); 
    Thread t1 = new Thread(new runHorses(h, 1)); 
    Thread t2 = new Thread(new runHorses(h, 2)); 
    Thread t3 = new Thread(new runHorses(h, 3)); 

    t0.start();
    t1.start();
    t2.start();
    t3.start();

    Thread.currentThread().run();

}

我怎样才能以正确的方式做到这一点? (我需要一个自动下注循环迭代,每25秒开始一次)

感谢。

2 个答案:

答案 0 :(得分:0)

通常,当您使用线程时,您可以使用锁定的变量(使用synchronize关键字)。 否则,您可以使用join()方法:

public void run() {
  // code
}


int main() {
    Thread t0 = new Thread(new runHorses(h, 0)); 
    Thread t1 = new Thread(new runHorses(h, 1)); 
    Thread t2 = new Thread(new runHorses(h, 2)); 
    Thread t3 = new Thread(new runHorses(h, 3)); 

    t0.start();
    t0.join();
    t1.start();
    t1.join();
    t2.start();
    t2.join();
    t3.start();
    t4.join();

}

答案 1 :(得分:0)

查看java.util.Timer课程,这正是您所需要的。