繁体   English   中英

线程启动/停止在Android上无法正常工作

[英]thread start/stop does not work correct on android

我需要一些有关启动/停止怪物的帮助。
我们生成如下:

for (int i = 0; i < 20; i++) {
    boolean notFree = true;
    int x = 0, y = 0;
    // while not free change
    // not determinstisch setting!
    while (notFree) {
        x = (int) (Math.random() * Config.XSIZE);
        y = (int) (Math.random() * Config.YSIZE);
        if (map.getMapPosition(x, y) == Config.EMPTYPOSITION) {
            notFree = false;
        }
    }
    switch ((int) Math.floor(Math.random() * 2)) {
    case 0:
        monsterVerktor.add(new Monster(context, x, y, this.map, 1,
                this.charac));
        break;
    case 1:
        monsterVerktor.add(new DeathReaper(context, x, y, this.map, 1,
                this.charac));
        break;
    default:
        break;
    }
}

然后我这样停止它们:(开始与开始移动相同)

public void stopAllMonsters() {
    for (Monster monster : monsterVerktor) {
        monster.getControl().stopMovingThread();
    }
 }

thread.stopMovingThread的工作方式如下:

public void stopMovingThread() {
    this.monster.setAlife(false);
    running = false;
    moveDone = true;
    boolean retry = true;
    while (retry) {
        try {
            thread.join();
            retry = false;
        } catch (InterruptedException e) {
            // try again shutting down the thread
        }
    }
}

到run():

public void startMovementThread() {
    running = true;
    thread = new Thread() {

        @Override
        public void run() {
            while (running) {
                Log.d(TAG, "run Thread");
                // get a little randomness in the movement ;)
                try {
                    // up to 0.5s sleeping till next moving
                    sleep(new Random().nextInt(Config.RANDOMSLEEP));
                } catch (InterruptedException e1) {}
                while (monster.isAlife()) {// check if alife
                    moveDone = false; // resett movement Done
                    noMove = false;
                    // Charakter in near if one is in near he
                    // will move to it.
                    if (!checkCharInAggroRange()) {
                        noMove = rndMove(); // if we have no move
                    }
                    while (!moveDone) {
                        timeBegin = System.currentTimeMillis();
                        // if hes not done with the move
                        if (monster.moveToX == monster.positionX
                            && monster.moveToY == monster.positionY) {
                            if (noMove) {
                                try {// sleep because no movement with a bit
                                        // randomness
                                    sleep(Config.MONSTERMOVINGTIME
                                        + (new Random()
                                                .nextInt(Config.RANDOMSLEEP)));
                                } catch (InterruptedException e) {
                                    Log.d(TAG,
                                        "An error occured during sleep because"
                                            + " of no Animatino");
                                }
                            }
                            // false after sleep
                            moveDone = false;
                            break; // already at the right position!
                            // movetoX is left of position
                        } else if (monster.moveToX > monster.positionX) {
                            monster.positionX++;
                            // movetoX is left of it
                        } else if (monster.moveToX < monster.positionX) {
                            monster.positionX--;
                            // movetoY is left of position
                        } else if (monster.moveToY > monster.positionY) {
                            monster.positionY++;
                            // movetoY is left of position
                        } else if (monster.moveToY < monster.positionY) {
                            monster.positionY--;
                        }
                        // sleep if hes moving to fast!
                        timeDiff = System.currentTimeMillis() - timeBegin;
                        sleepTimer = (int) (Config.MONSTERTIMING - timeDiff);
                        if (sleepTimer > 0) { // if >0 we are fast enough
                            // and can sleep a bit ;)
                            try {
                                sleep(sleepTimer);
                            } catch (InterruptedException e) {
                                Log.d(TAG, "Gameloop thread cant sleep");
                            }
                        }
                    }
                }
                try {
                    sleep(Config.RESPAWNTIMER);
                } catch (InterruptedException e) {
                    Log.d(TAG, "Monsterthread cant sleep");
                }
                // respawn it after a sleep :)
                respawn();
            }
        }
    };
    thread.start();
}

如果我们要停止它们并像这样启动它们,Android会停止工作,但我不明白为什么。 我们也像这样停止/开始渲染。 (嗯,这是可运行的,但不是)

Monster isAlife等:

public class Monster extends Drawable {

    private static final String TAG = Monster.class.getSimpleName();
    private int fullLife; // full life
    private int curLife; // current life
    public Context context;
    private Character charac;
    // ..
    // Basic monsterstuff
    private boolean alife, moveDone;
    private int level;
    public Status status;
    private MonsterControl control;

    // ..
    public Monster(Context context, int mapPosX, int mapPosY, Map map,
            int level, Character cha) {
        this.context = context;
        this.map = map;
        this.setCharac(cha);
        this.mapPosition[0] = mapPosX;
        this.mapPosition[1] = mapPosY;
        this.status = Status.IDLE;
        // example for full life calculation
        this.fullLife = level * 100 + ((int) (Math.random() * 10 * level)); // Examples
        this.curLife = this.fullLife;
        this.map.setMapPosition(mapPosX, mapPosY, Config.MONSTERSTATE);
        // set monster position
        // ..
        // load the sprite bitmap
        // ...
        // Change this later!
        alife = true;
        Log.d(TAG, "Monster created");
        // Starting the Controler
        control = new MonsterControl(this, this.charac);
        control.startMovementThread();
        Log.d(TAG, "Monster start moving");
        // exemplarisch cut of the sprite
        this.monsterPicAnimation();
    }
}

这里是生命的获取者/设定者

public boolean isAlife() {
    return alife;
}

public void setAlife(boolean alife) {
    this.alife = alife;
}

首先,您对“ Android停止运行”的评论,是否意味着崩溃? 得到了LogCat跟踪?

除此之外,此分析是否正确?

1.创建一个怪物。

running = true;
isAlife = true; //or whatever monster.isAlife() checks

2.线程启动。

while (running) {
  ...
  while (monster.isAlife()) {
    ...
  }
}

3.您尝试通过(1)设置为false并(2)加入该线程来停止线程吗?


假设这是真的。 怪物线程仍然运行,直到从嵌套while(monster.isAlife())循环中将其踢出为止。 一旦结束, while(running)将评估为false,线程应终止,然后移至集合中的下一个怪物。 没有这个终结,您将等待每个怪物死亡,同时使用join()锁定主线程。

除了我没有详细介绍的代码逻辑外,共享变量之间还缺乏同步。 尤其是,您的代码无法提供任何保证,即您的线程(在startMovementThread )将始终能够从主线程观察对标志所做的更改。

好的第一步是使这些变量易变:

private volatile boolean alife, moveDone;

但是请注意,可能还有其他问题(取决于您的要求)。 例如,当在startMovementThread中执行这些语句时:

if (monster.moveToX == monster.positionX ...)
monster.positionX++;

从主线程看不到对该线程所做的任何更改,反之亦然。 如果这可能是一个问题,那么您还需要同步访问这些变量(并且使它们变得易变是不够的,例如, monster.positionX++不是原子的)。

我自己以“好”主意解决了问题。 问题是,我让他们在某些时候睡觉。 如果他们睡着了,它就无法停止/加入线程,甚至不看它是否在“运行”。 所以我用一个看起来像这样的小方法解决了它:

private void breakableSleep(int i, int intervall){
    int x = 0;
    while(running && x <= i){
        try {
            this.thread.sleep(intervall);
        } catch (InterruptedException e) {
            Log.d(TAG, "Monsterthread cant sleep");
        }
        x++;
    }
}

它可以在每个间隔停止。 当然,这会花费一些电池,但是并没有找到其他方法以“快速”方式停止怪物,因为如果它们死了(重生),它们会睡大约3秒钟,所以我也重写了整个startMovementThread,因为我认为它看起来不太好。

最好的祝福

暂无
暂无

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

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