Android开发中,开启一个线程会占用多少内存空间?这个问题我一直没有测试过,以前在网上看见别人说需要1M内存(可能是该网友包含了很多数据),今天对这个问题做了一个测试。为了不影响测试,我使用空线程(线程不做任何事情,也不包含任何数据)。
先贴上测试代码
thread_occupy_memory.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <Button android:id="@+id/start_thread"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="开启一个新线程" />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="20dp"
- android:text="内存" />
- <TextView android:id="@+id/show_memoty"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
- </LinearLayout>
- import java.util.ArrayList;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.TextView;
- /**
- * 测试开启一个空线程会占用多少内存
- * @author DaveeChen
- */
- public class ThreadOccupyMemoryActivity extends Activity {
- private TextView mTextView;
- private ArrayList<Object> threadList = new ArrayList<Object>();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.setContentView(R.layout.thread_occupy_memory);
- init();
- }
- private void init() {
- this.findViewById(R.id.start_thread).setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- MyThread mMyThread = new MyThread();
- threadList.add(mMyThread);
- mMyThread.start();
- }
- });
- mTextView = (TextView)this.findViewById(R.id.show_memoty);
- mTextView.setText(analyzeMemory());
- }
- private String analyzeMemory() {
- Runtime mRuntime = Runtime.getRuntime();
- long usedMemory = mRuntime.totalMemory() - mRuntime.freeMemory();
- String result = "线程数量:"+threadList.size()
- +"\nUsedMemory:"+usedMemory
- +"bytes;\n"
- +"---------------------------------\n";
- return result;
- }
- private Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- if (msg.what == 1) {
- mTextView.setText(msg.obj.toString() + mTextView.getText());
- }
- }
- };
- private class MyThread extends Thread {
- @Override
- public void run() {
- mHandler.sendMessage(mHandler.obtainMessage(1, analyzeMemory()));
- while(true) {//让线程保持一直运行
- }
- }
- }
- }
在启动线程之前,已使用内存3015936字节(大约3015K)。启动一个线程后,内存已使用3030904(大约3030K),说明开启第一个线程使用了大约15K内存;
当开启了10个线程之后,内存已使用3071064(大约3071K),说明开启10个空线程大约用了55K内存。
我也测试了AsyncTask,占用内存和Thread差不多
- private class MyAsyncTask extends AsyncTask<Void,Void,Void> {
- @Override
- protected Void doInBackground(Void... params) {
- mHandler.sendMessage(mHandler.obtainMessage(1, analyzeMemory()));
- while(true) {//让线程保持一直运行
- }
- //return null;
- }
- }