Android Thread分析

2023-08-06  本文已影响0人  没有了遇见

学习一下线程相关东西

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

进程:(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 线程状态

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

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

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 */
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读