2013-12-08 58 views
0
private void stopThread() { 
    thread1.canRun(false); 
} 

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

} 

进出口创造了战舰的比赛中,线程启动,当用户用他的船射击,他有n秒拍摄,如果他们用完了,他失去了游戏.. 当他投篮最后一个线程停止并开始一个新的线程。这就是为什么我在创建线程中调用停止线程。2个线程运行一个比另一个

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 
      } 

      } 

     } 

的问题是,当我stopthread的为不应该继续运行和线程完成,但我认为当我开始新的线程canRun(真)遥遥领先“为”结构。 所以它改变了可变方式的第一个线程完成 因此它会继续运行,因为canRun是回真正的

我认为解决的办法是利用地方syncrhonized前 但林不知道.. 帮助谢谢

+0

你有你的声明变量canrun挥发性? –

+0

为什么'createThread'正在执行'thread1.canRun(true)'?你创建一个新的线程下面,可能可以运行 – zapl

+0

它不能运行,因为遍历“for”一个条件是canRun = true – AlanRubinoff

回答

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 ......