Android线程调用栈大小如何调整

发布时间:2020-10-26 17:58:25 作者:Leah
来源:亿速云 阅读:204

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();
      }
    }
  }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. jquery调整大小(resizable)
  2. linux如何无损调整分区大小

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android roi

上一篇:SQL Server中identity的使用方法

下一篇:UEditor实现自定义图片视频尺寸校验功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》