简体   繁体   English

我想,线程没有正确终止

[英]Thread not terminating correctly, I think

public String newUser = "false";
public double lat = 0.0, lon = 0.0;

I have the following function in my android app (called when a Button is clicked) which starts a thread: 我的android应用程序中有以下函数(单击一个Button时调用),它启动一个线程:

public void SignUpFunction(View view) {
    assignValues();
    String filledAll = checkIfFilled();
    if (filledAll.equals("true")) {
    Log.d("LIFECYCLE", "calling thread..");

    //my thread
    new validateThread().start();

    Log.d("After thread start","This log call does not occur");

    if (newUser.equals("true")) {
        Toast.makeText(this, "Please wait as we obtain your location", Toast.LENGTH_SHORT).show();
        getMyLocationFunction();
        } else {
            return;
        }
    }
}

validateThread: validateThread:

class validateThread extends Thread {
    public void run() {
        Log.d("LIFECYCLE", "validateThread entered...");
        try {
                        newUser = "true";
                        Log.d("validateThread", "Validated and found new user");
        } catch (Exception e) {
            Log.d("validateThread", "Exception in validateThread: " + e.getMessage());
        }
    }
}

The thread runs correctly...but after the last line, it does not go back to its point of start. 线程正确运行...但在最后一行之后,它不会回到它的起始点。 I don't understand why this is happening because I've used threads before and they all work correctly. 我不明白为什么会发生这种情况,因为我之前使用过线程并且它们都正常工作。

I know I can just give the getMyLocation function inside the thread but I really need it this way. 我知道我可以在线程中提供getMyLocation函数,但我确实需要这种方式。

I've searched for similar questions but none helped.. What am I doing wrong here? 我搜索过类似的问题,但没有人帮忙..我在这里做错了什么? Thanks in advance. 提前致谢。

It's a race. 这是一场比赛。 SignUpFunction should wait until validateThread decides whether or not to set newUser = "true". SignUpFunction应该等到validateThread决定是否设置newUser =“true”。 Even with the race your code may work sometimes, but that is by accident. 即使在竞争中,您的代码有时也会起作用,但这是偶然的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM