android 多线程

来源:互联网 发布:淘宝开店需要押金么 编辑:程序博客网 时间:2024/06/11 11:46

在android4.0以后不允许主线程进行网络的访问,这样我们就必须进行多线程的操作,才能对网络进行访问;在现实我们的activity时,我们的onCreate()、onStart()、onResume()方法的执行时间决定了你的应用首页打开的时间,这里要尽量把不必要的操作放到其他线程去处理,如果仍然很耗时。

多线程: 在android 开启一个app的时候就会产生一个main线程,在main 线程中我们可以操作ui(ui只能在main 中进行操作),如果在主线程中有很耗时的服务比如,解析xml文件等,会导致activity不能及时的显示,很可能在一段时间后被杀死,所以我们需要新建一个线程来进行处理


在实现多线程的操作中,有2种方式,一种是继承 Thread类,还有一种是实现RunAble接口,


线程类必须实现run方法,在run方法中写出你要在这个线程中所要做的事情:

public class MyThread  extends Thread {    @Override    public void run() {        super.run();        HttpRequest httpRequest = new HttpRequest("http://www.baidu.com/");        String result = httpRequest.httpGet();    }}

我们在activity中进行调用:

 MyThread myThread = new MyThread();       MyThread.run();        myThread.start();
这样就启动了另外一个线程,在线程启动的时候必须调用start方法,才能启动线程


线程调用还可以这样写,为了方便吧:

new Thread(new Runnable() {            @Override            public void run() {                HttpRequest httpRequest = new HttpRequest("http://www.baidu.com");                httpRequest.httpGet();            }        }).start();



0 0
原创粉丝点击