2014-04-04 64 views
0

通过this看后,我试图阻止一个线程,这里就是我有停止线程Java的方式

Thread restartLocation = new Thread(new Runnable() { 
    @Override 
    public void run() { 
     while (true) { 
      try { 
       Thread mThis = Thread.currentThread(); 
       while(restartLocation == mThis) { 
        for(int i = 0; i < 10; i++) { 
         Log.d("Delay", i+" seconds"); 
         Thread.sleep(1000); 
        } 

        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          map.setMyLocationEnabled(true); 
         } 
        }); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

    } 
}); 

//When the map is drag stop it update with the users location 
//If the user drags the map to look around they dont want it moving back 
mf.setOnDragListener(new TouchableWrapper.OnDragListener() { 
    @Override 
    public void onDrag(MotionEvent motionEvent) { 
     map.setMyLocationEnabled(false); 
     Log.d("Map", "Stopped location and remove drag listener"); 
     if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { 

      //Stop restartLocation if it's running 
      restartLocation.start(); 
     } 
    } 
}); 

不过,我在这条线while(restartLocation == mThis) {变量restartLocation可能没有得到一个错误初始化。我该如何解决这个错误?或者,有没有更好的方法可以阻止此线程?

+0

在创建'restartLocation'对象时,您正在尝试使用它,因此编译器正在抛出未初始化的错误。 – Reddy

+0

为什么你认为调用'restartLocation.start()'会停止restartLocation线程?请阅读http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html –

+0

我不这样做,注释'//停止restartLocation(如果它正在运行)是我最终找到的停止代码的占位符。 –

回答

0

您正尝试在其初始化本身内使用restartLocation引用。它尚未初始化。您不能使用它,直到它被初始化。这就是为什么错误!

+0

就编译器能够证明的内容而言,您的回答是正确的。但是,也许Tom Hart感到困惑的原因是,他知道那个运行方法在分配完成之后才会被调用。那是因为他知道编译器不知道的东西。他知道Thread类的行为。 –

+0

@jameslarge是的,你是对的。谢谢! – Keerthivasan

0

使restartLocation成为一个成员变量。由于成员初始化为默认值(在这种情况下为null),所以错误应该消失。 。

当然,这仅仅是因为你鸵鸟政策给你的代码在运行环境中的任何信息建议

然而,你的代码包含了另一个错误:一个匿名类必须的范围之内 变量被宣布为final以便可以从匿名类内访问。在你的代码中,你不能读取restartLocation,因为它没有被声明为final