中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android線程調用棧大小如何調整

發布時間:2020-10-26 17:58:25 來源:億速云 閱讀:205 作者:Leah 欄目:開發技術

Android線程調用棧大小如何調整?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

在常規的Android開發過程中,隨著業務邏輯越來越復雜,調用棧可能會越來越深,難免會遇到調用棧越界的情況,這種情況下,就需要調整線程棧的大小。

當然,主要還是增大線程棧大小,尤其是存在jni調用的情況下,C++層的棧開銷有時候是非常恐怖的,比如說遞歸調用。

這就需要分三種情況,主線程,自定義線程池,AsyncTask。

主線程的線程棧是沒有辦法進行修改的,這個沒辦法處理。

針對線程池的情況,需要在創建線程的時候,調用構造函數

public Thread(@RecentlyNullable ThreadGroup group, @RecentlyNullable Runnable target, @RecentlyNonNull String name, long stackSize)

通過設置stackSize參數來解決問題。

參考代碼如下:

import android.support.annotation.NonNull;
import android.util.Log;

import java.util.concurrent.ThreadFactory;

/**
 * A ThreadFactory implementation which create new threads for the thread pool.
 */
public class SimpleThreadFactory implements ThreadFactory {
  private static final String TAG = "SimpleThreadFactory";
  private final static ThreadGroup group = new ThreadGroup("SimpleThreadFactoryGroup");
  // 工作線程堆棧大小調整為2MB
  private final static int workerStackSize = 2 * 1024 * 1024;

  @Override
  public Thread newThread(@NonNull final Runnable runnable) {
    final Thread thread = new Thread(group, runnable, "PoolWorkerThread", workerStackSize);
    // A exception handler is created to log the exception from threads
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(@NonNull Thread thread, @NonNull Throwable ex) {
        Log.e(TAG, thread.getName() + " encountered an error: " + ex.getMessage());
      }
    });

    return thread;
  }
}
import android.support.annotation.AnyThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * A Singleton thread pool
 */
public class ThreadPool {
  private static final String TAG = "ThreadPool";
  private static final int KEEP_ALIVE_TIME = 1;
  private static volatile ThreadPool sInstance = null;
  private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
  private final ExecutorService mExecutor;
  private final BlockingQueue<Runnable> mTaskQueue;

  // Made constructor private to avoid the class being initiated from outside
  private ThreadPool() {
    // initialize a queue for the thread pool. New tasks will be added to this queue
    mTaskQueue = new LinkedBlockingQueue<>();

    Log.d(TAG, "Available cores: " + NUMBER_OF_CORES);

    mExecutor = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES * 2, KEEP_ALIVE_TIME, TimeUnit.SECONDS, mTaskQueue, new SimpleThreadFactory());
  }

  @NonNull
  @AnyThread
  public static ThreadPool getInstance() {
    if (null == sInstance) {
      synchronized (ThreadPool.class) {
        if (null == sInstance) {
          sInstance = new ThreadPool();
        }
      }
    }
    return sInstance;
  }

  private boolean isThreadPoolAlive() {
    return (null != mExecutor) && !mExecutor.isTerminated() && !mExecutor.isShutdown();
  }

  @Nullable
  @AnyThread
  public <T> Future<T> submitCallable(@NonNull final Callable<T> c) {
    synchronized (this) {
      if (isThreadPoolAlive()) {
        return mExecutor.submit(c);
      }
    }
    return null;
  }

  @Nullable
  @AnyThread
  public Future<&#63;> submitRunnable(@NonNull final Runnable r) {
    synchronized (this) {
      if (isThreadPoolAlive()) {
        return mExecutor.submit(r);
      }
    }
    return null;
  }

  /* Remove all tasks in the queue and stop all running threads
   */
  @AnyThread
  public void shutdownNow() {
    synchronized (this) {
      mTaskQueue.clear();
      if ((!mExecutor.isShutdown()) && (!mExecutor.isTerminated())) {
        mExecutor.shutdownNow();
      }
    }
  }
}

針對AsyncTask的情況,一般是通過調用

public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params)

指定線程池來運行,在特定的線程池中調整線程棧的大小。

參考代碼如下:

import android.os.AsyncTask;
import android.support.annotation.AnyThread;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class AsyncTaskEx<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

  private static final String TAG = "AsyncTaskEx";
  private static final int KEEP_ALIVE_TIME = 1;
  private static volatile ThreadPool sInstance = null;
  private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
  private final ExecutorService mExecutor;
  private final BlockingQueue<Runnable> mTaskQueue;

  public AsyncTaskEx() {
    // initialize a queue for the thread pool. New tasks will be added to this queue
    mTaskQueue = new LinkedBlockingQueue<>();

    Log.d(TAG, "Available cores: " + NUMBER_OF_CORES);

    mExecutor = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES * 2, KEEP_ALIVE_TIME, TimeUnit.SECONDS, mTaskQueue, new SimpleThreadFactory());
  }

  public AsyncTask<Params, Progress, Result> executeAsync(@NonNull final Params... params) {
    return super.executeOnExecutor(mExecutor, params);
  }

  /* Remove all tasks in the queue and stop all running threads
   */
  @AnyThread
  public void shutdownNow() {
    synchronized (this) {
      mTaskQueue.clear();
      if ((!mExecutor.isShutdown()) && (!mExecutor.isTerminated())) {
        mExecutor.shutdownNow();
      }
    }
  }
}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

迁西县| 电白县| 大安市| 长岭县| 广东省| 宿松县| 岗巴县| 桓台县| 山东| 阆中市| 炎陵县| 门头沟区| 井冈山市| 石嘴山市| 闽侯县| 南部县| 清原| 甘德县| 民乐县| 昔阳县| 灯塔市| 湖口县| 孟津县| 湘乡市| 申扎县| 岳普湖县| 安国市| 孟连| 普安县| 泰安市| 扶余县| 黎城县| 清苑县| 东兰县| 通化市| 靖远县| 盐池县| 开封市| 莱阳市| 长顺县| 海原县|