Android多線程(二)

線程、進(jìn)程、協(xié)程

  • 進(jìn)程 進(jìn)程是計(jì)算機(jī)資源調(diào)度和分配的單位。是程序的實(shí)體。計(jì)算機(jī)將自己的內(nèi)存資源,CPU資源分配給不同的進(jìn)程,這樣程序才得以運(yùn)行。
  • 線程 線程是計(jì)算機(jī)運(yùn)算的最小調(diào)度單位。線程依附于進(jìn)程,一個(gè)進(jìn)程至少有一個(gè)線程。線程沒有自己的內(nèi)存,而使用進(jìn)程的內(nèi)存。進(jìn)程調(diào)度一個(gè)或多個(gè)線程進(jìn)行運(yùn)算。
  • 協(xié)程 協(xié)程其實(shí)沒有統(tǒng)一的定義。一般來說,協(xié)程是單線程內(nèi)實(shí)現(xiàn)并發(fā)、非阻塞執(zhí)行。kotlin中的協(xié)程實(shí)際上線程、只不過與傳統(tǒng)的線程看起來不太一樣。

線程的創(chuàng)建方式

線程的創(chuàng)建需要有系統(tǒng)的支持,所以在代碼中,創(chuàng)建代碼的方式本質(zhì)上就幾種,以及在其上做的一些封裝。

  • 使用Thread類創(chuàng)建線程。Thread#start()是native方法,調(diào)用這個(gè)方法后,進(jìn)程會創(chuàng)建一個(gè)新線程,并且在新的線程里面執(zhí)行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();
        }
    }
    

所以,使用Thread類創(chuàng)建線程又有兩種方式,1.創(chuàng)建一個(gè)Runnable對象作為target。2.創(chuàng)建一個(gè)Thread的子類,重寫run()方法。

  • 使用線程池創(chuàng)建和管理多線程。頻繁的創(chuàng)建和切換線程,對于JVM會造成很大的負(fù)擔(dān)。使用線程池即使可以降低這種負(fù)擔(dān)。線程池本質(zhì)上也是使用Thread,但是線程池提供了線程的復(fù)用方法。當(dāng)一個(gè)線程結(jié)束后,根據(jù)之前線程池的設(shè)定,不會馬上回收,而是等待一段時(shí)間,一段時(shí)間內(nèi)如果用多線程任務(wù)的話,復(fù)用這個(gè)線程。線程池的基本構(gòu)造方法如下
    /**
       * Creates a new {@code ThreadPoolExecutor} with the given initial
       * parameters.
       *
       * @param corePoolSize the number of threads to keep in the pool, even
       *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
       * @param maximumPoolSize the maximum number of threads to allow in the
       *        pool
       * @param keepAliveTime when the number of threads is greater than
       *        the core, this is the maximum time that excess idle threads
       *        will wait for new tasks before terminating.
       * @param unit the time unit for the {@code keepAliveTime} argument
       * @param workQueue the queue to use for holding tasks before they are
       *        executed.  This queue will hold only the {@code Runnable}
       *        tasks submitted by the {@code execute} method.
       * @param threadFactory the factory to use when the executor
       *        creates a new thread
       * @param handler the handler to use when execution is blocked
       *        because the thread bounds and queue capacities are reached
       * @throws IllegalArgumentException if one of the following holds:<br>
       *         {@code corePoolSize < 0}<br>
       *         {@code keepAliveTime < 0}<br>
       *         {@code maximumPoolSize <= 0}<br>
       *         {@code maximumPoolSize < corePoolSize}
       * @throws NullPointerException if {@code workQueue}
       *         or {@code threadFactory} or {@code handler} is null
       */
      public ThreadPoolExecutor(int corePoolSize,
                                int maximumPoolSize,
                                long keepAliveTime,
                                TimeUnit unit,
                                BlockingQueue<Runnable> workQueue,
                                ThreadFactory threadFactory,
                                RejectedExecutionHandler handler) {
          if (corePoolSize < 0 ||
              maximumPoolSize <= 0 ||
              maximumPoolSize < corePoolSize ||
              keepAliveTime < 0)
              throw new IllegalArgumentException();
          if (workQueue == null || threadFactory == null || handler == null)
              throw new NullPointerException();
          this.corePoolSize = corePoolSize;
          this.maximumPoolSize = maximumPoolSize;
          this.workQueue = workQueue;
          this.keepAliveTime = unit.toNanos(keepAliveTime);
          this.threadFactory = threadFactory;
          this.handler = handler;
      }  
    
  • 以Android中的其他方式創(chuàng)建線程,如AsycTask,IntentService等,這些本質(zhì)上都是對Thread的封裝,在這里就不做詳細(xì)介紹

Android多線程(一)
Android多線程(三)
Android多線程(四)
Android多線程(五)
Android多線程(六)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容