Android Thread分析

学习一下线程相关东西

什么是线程?什么是进程?

进程:(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配的基本单位,是操作系统结构的基础.Android 系统中 一个App就是一个进程(或多个进程)

线程:(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程中的实际运作单位。Android中 App运行在主线程中

1:创建线程方式
方式1.创建Runable 方式
      Runnable runnable=  new Runnable(){
            @Override
            public void run() {
                
            }
        };
        new Thread(runnable).start();

2.方式2 实现Runable 接口方式
       new Thread(){
            @Override
            public void run() {
                super.run();
                
            }
        }.start();



2.Thread.run() 和Thread.start()区别

**run:**是Runable接口的方法, Thread实现了这个接口,Thread调用run方式只是调用了Thread 的run方法而已

/**
     * If this thread was constructed using a separate
     * {@code Runnable} run object, then that
     * {@code Runnable} object's {@code run} method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of {@code Thread} should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

start: 使此线程开始执行 调用Native方法创建线程 并且执行线程线程变成 started状态

   /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the {@code run} method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * {@code start} method) and the other thread (which executes its
     * {@code run} method).
     * <p>

     * It is never legal to start a thread more than once.
        一个线程启动多次是不合法的。
     * In particular, a thread may not be restarted once it has completed
     * execution.
          特别是,线程一旦完成就可能无法重新启动执行
     *
     * @throws     IllegalThreadStateException  if the thread was already started.
     * @see        #run()
     * @see        #stop()
     */
    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: Replace unused threadStatus field with started field.
        // The threadStatus field is unused on Android.
        // if (threadStatus != 0)
    //多次执行后会抛出异常,除非执行结束后挂起
        if (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);

        // Android-changed: Use field instead of local variable.
        // It is necessary to remember the state of this across calls to this method so that it
        // can throw an IllegalThreadStateException if this method is called on an already
        // started thread.
        // boolean started = false;
        started = false;
        try {
            // Android-changed: Use Android specific nativeCreate() method to create/start thread.
            // start0();
            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 */
            }
        }
    }

4.线程状态

Thread.State 线程状态

  • Thread.State.NEW Thread thread=new Thread;
    线程刚创建,尚未启动的线程的线程状态

  • Thread.State.RUNNABLE thread.start();
    可运行线程的线程状态。处于可运行状态的线程正在Java虚拟机中执行,但它可能正在等待来自操作系统的其他资源,例如处理器。

  • Thread.State.BLOCKED 该状态是线程因为某种原因放弃了cpu使用权限,暂时停止运行
    被阻止等待监视器锁定的线程的线程状态。处于阻塞状态的线程正在等待监视器锁进入同步的块/方法,或者在调用Object.wait后重新进入同步块/方法。

阻塞的情况有三种:
1)等待:调用了wait(),线程进入等待阻塞状态。此时线程需要等待某项工作的完成
2)同步:当线程获取synchronized同步锁失败(此时锁被其他线程暂时占用),线程进入同步阻塞状态。此时该线程需要等其他线程使用完锁。
3)其他:当调用了sleel()或join()或发出了I/O请求时,线程进入阻塞状态。此时线程需要等sleep()时间结束或被打断、join()中断、I/O处理完成,线程才能重新进入就绪状态。


  • Thread.State.WAITING
    等待线程的线程状态。由于调用以下方法之一,线程处于等待状态:
    • Object.wait :无超时的对象等待
    • Thread.join无超时的线程联接
    • 锁定Support.park

处于等待状态的线程正在等待另一个线程执行特定操作。例如,对某个对象调用了Object.wait()的线程正在等待另一个线程对该对象调用Object.notify()或Object.notifyAll()。一个调用了thread.join()的线程正在等待指定的线程终止。

  • Thread.State.TIMED_WAITING
    处于等待状态的线程正在等待另一个线程执行特定操作。例如,对某个对象调用了Object.wait()的线程正在等待另一个线程对该对象调用Object.notify()或Object.notifyAll()。一个调用了thread.join()的线程正在等待指定的线程终止。
  • Thread.State.TERMINATED
    具有指定等待时间的等待线程的线程状态。由于在指定的正等待时间内调用以下方法之一,线程处于定时等待状态:
    • Thread.sleep
    • Object.wait with timeout
    • Thread.join with timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil
1)线程中run()或call()执行完成,正常结束
2)线程抛出Exception或error,异常退出
3)线程调用stop()结束—容易导致死锁,不建议

注意:
start()一个线程只能执行一次,再次执行会报异常
started赋值为true再次运行直接抛异常

  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: Replace unused threadStatus field with started field.
        // The threadStatus field is unused on Android.
        // if (threadStatus != 0)
        if (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);

        // Android-changed: Use field instead of local variable.
        // It is necessary to remember the state of this across calls to this method so that it
        // can throw an IllegalThreadStateException if this method is called on an already
        // started thread.
        // boolean started = false;
        started = false;
        try {
            // Android-changed: Use Android specific nativeCreate() method to create/start thread.
            // start0();
            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 */
            }
        }
    }

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。
img
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。

欢迎大家一键三连支持,若需要文中资料,直接扫描文末CSDN官方认证微信卡片免费领取↓↓↓(文末还有ChatGPT机器人小福利哦,大家千万不要错过)

PS:群里还设有ChatGPT机器人,可以解答大家在工作上或者是技术上的问题
图片

  • 15
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值