通过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可能没有得到一个错误初始化。我该如何解决这个错误?或者,有没有更好的方法可以阻止此线程?
在创建'restartLocation'对象时,您正在尝试使用它,因此编译器正在抛出未初始化的错误。 – Reddy
为什么你认为调用'restartLocation.start()'会停止restartLocation线程?请阅读http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html –
我不这样做,注释'//停止restartLocation(如果它正在运行)是我最终找到的停止代码的占位符。 –