多线程问题,而编程的机器人 [英] MultiThreading issues while programing for android

查看:126
本文介绍了多线程问题,而编程的机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发在Android上,但问题可能只是任何其他Java平台是有效的。

I am developing on Android but the question might be just as valid on any other Java platform.

我公司开发的多线程应用程序。可以说,我有一个需要做一个时间密集型任务一流,因此这项工作是在另一个线程中完成的。 当它这样做了相同的线程将时间密集型任务,结​​果返回到另一个(3)班。

I have developed a multi-threaded app. Lets say I have a first class that needs to do a time-intensive task, thus this work is done in another Thread. When it's done that same Thread will return the time-intensive task result to another (3rd) class.

这最后一堂课会做一些事情,并返回它的结果为第一出发类。 我注意到,虽然第一类将是等待的全部时间,也许是因为这是某种形式的循环?

This last class will do something and return it's result to the first-starting class. I have noticed though that the first class will be waiting the whole time, maybe because this is some kind of loop ?

另外,我想线程级停止本身,在当它已经通过它的产生到第三级就应该停止。第三类有做的工作,而在第二类(线程一)被封装。 任何人都知道如何做到这一点?

Also I'd like the Thread-class to stop itself, as in when it has passed it's result to the third class it should simply stop. The third class has to do it's work without being "encapsulated" in the second class (the Thread one). Anyone knows how to accomplish this ?

现在的经验是,第一个似乎在等待(悬挂),直到第二个和第三个完成:(

right now the experience is that the first one seems to be waiting (hanging) till the second and the third one are done :(

推荐答案

如果你想使用线程,而不是一个的AsyncTask 你可以做这样的事情:

If you want to use threads rather than an AsyncTask you could do something like this:

private static final int STEP_ONE_COMPLETE = 0;
private static final int STEP_TWO_COMPLETE = 1;

...

private doBackgroundUpdate1(){
    Thread backgroundThread = new Thread() {
        @Override
        public void run() {
            // do first step

            // finished first step
            Message msg = Message.obtain();
            msg.what = STEP_ONE_COMPLETE;
            handler.sendMessage(msg);
        }
    }
    backgroundThread.start();
}
private doBackgroundUpdate2(){
    Thread backgroundThread = new Thread() {
        @Override
        public void run() {
            // do second step

            // finished second step
            Message msg = Message.obtain();
            msg.what = STEP_TWO_COMPLETE;
            handler.sendMessage(msg);
        }
    }
    backgroundThread.start();
}
private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case STEP_ONE_COMPLETE:
            doBackgroundUpdate2();
            break;
        case STEP_TWO_COMPLETE:
            // do final steps;
            break;
        }
    }
}

您会通过调用 doBackgroundUpdate1(),此操作完成之后将消息发送到处理揭开序幕 doBackgroundUpdate2()等。

You would kick it off by calling doBackgroundUpdate1(), when this is complete it sends a message to the handler which kicks off doBackgroundUpdate2() etc.

这篇关于多线程问题,而编程的机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆