简体   繁体   English

Java和Android的线程问题

[英]Threading Problem with Java and Android

I'm designing an app, which flicks through a series of pictures, like flicking through a photo album. 我正在设计一个应用程序,可以浏览一系列图片,就像浏览相册一样。 Pretty standard stuff I'm sure. 我敢肯定,这是标准的东西。 Since the picture must be viewed for a few seconds before it automatically changes ot the next pic, I decided to ake a thread that shows the pic, waits couple of second and then moves on. 由于必须先查看图片几秒钟,才能自动更改下一张图片,因此我决定创建一个显示图片的线程,等待几秒钟,然后继续前进。

Picthread(ImageView Image1) {
        this.image = Image1;

    }

    public void run(){

        showPicture(image);
        animal_array = new String[7];

        while (counter < 7){
            try{


                int timer = 0;

                while (timer < 2000){

                    sleep(500);

                    timer+=500;
                }
                image.post(new Runnable(){

                    public void run() {

                         showPicture(image);


                    }

                });



            }
             catch (InterruptedException e) {  
                } 
        }




    }

This actualy worked. 这实际上是有效的。 showPictures is a very simple method that just chooses a picture and puts it on an ImageView. showPictures是一种非常简单的方法,它只选择一张图片并将其放在ImageView上。 It isn't necessary to know about it for my problem. 对于我的问题,不必了解它。 At first itdidn't work, the logcat said I couldn't touch a view on a view heirarchy that wasnt created in this thread. 起初它没有用,logcat说我无法在该线程中未创建的视图层次结构上触摸视图。 I wasn't sure what that meant so I did the 我不确定这是什么意思,所以我做了

image.post(...)

code. 码。 Which worked. 哪个有效。 My main question is: Why was this necesary? 我的主要问题是:为什么要这样做? If you look at my above code, the first showPicture() method is not inside the image.post() code. 如果看上面的代码,第一个showPicture()方法不在image.post()代码内。 But no exception is registered. 但没有例外。 I don't understand this, why isn't a post needed? 我不明白,为什么不需要帖子? But also why do I need to post, since Image is a class variable, and I thought could be viewed by all threads. 还有为什么我需要发布,因为Image是一个类变量,并且我认为可以被所有线程查看。 I was happy it worked, but puzzled. 我很高兴它奏效,但感到困惑。

Please bare in mind, this is my first attempt at threading in Java on anything more than trivial textbook examples. 请记住,这是我首次尝试在Java线程上进行琐碎的教科书示例以外的操作。 SO I'm still pretty confused. 所以我还是很困惑。

By the way, in the end I ditched the whole thread, and just did 顺便说一句,最后我放弃了整个线程,只是做了

new Thread(new Runnable() {
            public void run() {...}

When doing "things" with the GUI you should always be on the GUI thread. 使用GUI进行“操作”时,您应该始终在GUI线程上。 That is what View.post(Runnable) does, ensuring that the gui thread does the work of the runnable. 这就是View.post(Runnable)所做的,确保gui线程完成了runnable的工作。

Even though your showImage works once does not mean that it always works... 即使您的showImage可以运行一次,也并不意味着它总是可以运行...

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

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