Android创建线程的方式及启动方式分析

本文介绍两方面的知识:

一.创建线程的两种方式

二.启动线程start和run的分析

 

一.创建线程的两种方式

    java提供两种创建线程的方式:

1.继承Thread

private void createThread(){
    new MyThread().start();
}


private class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
            Thread.sleep(1000);//子线程中处理耗时操作
        }catch (Exception e){

        }
    }
}

2.实现runnable接口

private void createThreadByRunnable(){
    new Thread(new MyThreadRunnable()).start();
}

private class MyThreadRunnable implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(1000);//子线程中处理耗时操作
        }catch (Exception e){
        }
    }
}

两者使用方式对比:

1.Java不允许多继承,所以如果采用继承Thread的方式就不能继承其他类,降低了类的扩展性,而实现Runnable接口就可以继承其他类。

2.使用Runnable创建的线程可以实现多个线程访问同一个资源。

 

接下来看下线程两种启动方式:start()和run()的区别:

private void createThread(){
        new MyThread().start();
//        new MyThread().run();
    }
    private class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            Log.e(TAG,Thread.currentThread().getName());
            mBtn.setText("start");
        }

    }

我们先看start()启动方式,运行程序发现程序报错了:

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

说更新ui只能在主线程中更新,说明用start方式是启动了一个子线程。

 

接下来我们看下run()方式:

 private void createThread(){
//        new MyThread().start();
        new MyThread().run();
    }
    private class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            Log.e(TAG,Thread.currentThread().getName());
            mBtn.setText("start");
        }

    }

发现程序正常运行,且btn更新为start,log中出现的线程名字为”main”:Main2Activity: main,

说明用run()方式并没有开启一个子线程,run还是运行在主线程中。

这就是两种启动方式的区别。

 

我们来看下两个方法的源码:

start():可以看到start方法中调用了nativeCreate创建了线程:

public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    // Android-changed: throw if 'started' is true
    if (threadStatus != 0 || started)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    started = false;
    try {
        nativeCreate(this, stackSize, daemon);
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

而run方法,只是执行了runnable中的run方法。

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值