一个在另一个上运行的2个线程

时间:2013-12-08 13:17:34

标签: java multithreading synchronization

 private void stopThread() {
    thread1.canRun(false);
}

private void createThread() {
    thread1.stopThread();
    thread1.canRun(true);
    thread1 = new Thread(thread1);
    t.start();

}

我正在创建一个战舰游戏,当用户用他的船射击时,线程开始,他有n秒的时间进行射击,如果他们用尽,他就会失去游戏。 当他再次射击时,最后一个线程停止并开始一个新线程。 这就是为什么我在创建线程中调用stop thread。

public void canRun(boolean canrun) {
    this.canrun= canrun;
}

public thread(player player, gamej) throws RemoteException {
    this.player= player;
    this.j = j;
    tiempoTimeOut = j.getTimeout();

}

@Override
public void run() {

    try {
        for (int i = 0; i <= TimeOut && canRun; i++) {

            // System.out.println(i);

            Thread.sleep(1000);
            if (i ==tiempoTimeOut) {
                j.notifiy();//the player lost code irrelevant
            }

            }

        }

问题是,当我停止传输for不应该继续运行并且线程结束但我认为当我开始新线程时,canRun(true)远远超过&#34;对于&#34;结构体。 所以它在第一个线程完成之前改变了变量方式 所以它继续运行因为canRun回归真实

我认为解决方案是在某处使用syncrhonized 但我不确定.. 谢谢你

1 个答案:

答案 0 :(得分:0)

您可以使用Thread.currentThread.isInterruptted()代替canRun变量。 比如

private void stopThread() {
    thread1.interrupt();
}

private void createThread() {
    thread1.stopThread();
    thread1 = new Thread(thread1);
    thread1.start();
}

并且run方法可以像这样

public run() {
    try {
        for (int i = 0; i <= TimeOut && !Thread.currentThread.isInterrupted(); i++) {

            // System.out.println(i);

            Thread.sleep(1000);
            if (i ==tiempoTimeOut) {
                j.notifiy();//the player lost code irrelevant
            }

        }

    } catch ......
相关问题