以Java方式停止线程

以Java方式停止线程,java,multithreading,Java,Multithreading,看完后,我试图阻止一个线程,这是我的 Thread restartLocation = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread mThis = Thread.currentThread(); while(restartLocation == mTh

看完后,我试图阻止一个线程,这是我的

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();
        }
    }
});
Thread restartLocation=新线程(new Runnable(){
@凌驾
公开募捐{
while(true){
试一试{
Thread mThis=Thread.currentThread();
while(restartLocation==mThis){
对于(int i=0;i<10;i++){
Log.d(“延迟”,i+“秒”);
睡眠(1000);
}
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
map.setMyLocationEnabled(true);
}
});
}
}捕获(例外e){
e、 printStackTrace();
}
}
}
});
//当地图被拖动停止时,它将随用户位置更新
//如果用户拖动地图环顾四周,他们不希望地图向后移动
mf.setOnDragListener(新的TouchableWrapper.OnDragListener(){
@凌驾
公共空间onDrag(MotionEvent MotionEvent){
map.setMyLocationEnabled(false);
Log.d(“映射”、“停止位置并移除拖动侦听器”);
if(motionEvent.getActionMasked()==motionEvent.ACTION\u UP){
//如果正在运行,请停止restartLocation
restartLocation.start();
}
}
});

但是,我在这一行
while(restartLocation==mThis)上得到一个错误{
变量restartLocation可能尚未初始化。如何修复此错误?或者,是否有更好的方法停止此线程?

您正在尝试在其初始化本身中使用
restartLocation
引用。它尚未初始化。在初始化之前无法使用它。这就是错误的原因!

Make
restartLocation
a成员变量。由于成员是用默认值初始化的(在这种情况下为null),因此错误应该消失

当然,这只是一个建议,因为您没有提供有关代码运行环境的任何信息

但是,您的代码包含另一个错误:
匿名类范围之外的变量必须声明为
final
,才能从匿名类中访问。在代码中,您将无法读取
restartLocation
,因为它未声明为
final

,当您创建
restartLocation
对象时,您正在尝试使用它,所以编译器抛出了未初始化的错误。为什么您认为调用
restartLocation.start()
会停止restartLocation线程吗?我不知道,如果restartLocation正在运行,注释
//stop restartLocation
是我最终找到的停止代码的占位符。就编译器所能证明的而言,您的答案是正确的。但可能Tom Hart感到困惑的原因是,他知道run方法实际上不会被调用直到赋值完成后,他才知道。这是因为他知道编译器不知道的东西。他知道Thread类的行为。