好记性不如铅笔头

android, java, 数据结构与算法, 编程

Android应用开发笔记:自定义的线程池

最近考虑一种情形,当页面快速上下刷新的时候,我们如何才能减少资源消耗,作者最近自己写了一个自定义的线程池,用来缓解页面快速上下刷新的情况。

代码:

public class GifThreads
{
	public static interface GifRunnable
	{
		public Integer getid();
		public void run();
		public void stop();
	}
	
	public static final GifThreads Instance = new GifThreads();
	private GifThreads()
	{}

	private static final int MAX_TRHEAD = 5;
	
	private HashMap<Integer, MyThread> hashMap = new HashMap<Integer, MyThread>();
	
	public void addFun(GifRunnable run)
	{
		if (null == run)
		{
			return;
		}
		if (hashMap.get(run.getid()) != null)
		{
			return;
		}
		if (hashMap.size() >= MAX_TRHEAD)
		{
			return;
		}
		MyThread newThread = new MyThread(run);
		hashMap.put(run.getid(), newThread);
		newThread.start();
	}
	
	public void stopFun(Integer id)
	{
		MyThread thread = hashMap.get(id);
		if (null == thread)
		{
			return;
		}
		
		hashMap.remove(id);
		if (thread.isAlive())
		{
			thread.onCancel();
		}
	}
	
	private static class MyThread extends Thread
	{
		private boolean isCancel = false;
		private GifRunnable interfaceRun;
		public MyThread(GifRunnable interfaceRun)
		{
			super();
			this.interfaceRun = interfaceRun;
		}

		public void onCancel()
		{
			isCancel = true;
			interfaceRun.stop();
		}

		@Override
		public void run()
		{
			try
			{
				Thread.sleep(100);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			if (isCancel)
			{
				System.out.println("canceled before run" + interfaceRun.getid());
				return;
			}
			interfaceRun.run();
			
			System.out.println("thread finished:" + interfaceRun.getid());
		}
	}
}

 使用方式:

实现接口:

class gif implements  GifThreads.GifRunnable
{
	private int x;
	public gif(int x)
	{
		this.x = x;
	}
	@Override
	public Integer getid()
	{
		return x;
	}

	@Override
	public void run()
	{
		while(!b)
		{
			System.out.println("this is " + x);
			try
			{
				Thread.sleep(1500);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	boolean  b = false;
	@Override
	public void stop()
	{
		b = true;
	}
}

 调用方法:

GifThreads.Instance.addFun(new gif(0));
GifThreads.Instance.addFun(new gif(1));
GifThreads.Instance.addFun(new gif(2));
GifThreads.Instance.addFun(new gif(3));
GifThreads.Instance.addFun(new gif(4));
GifThreads.Instance.addFun(new gif(4));//可以多次添加
GifThreads.Instance.addFun(new gif(4));
GifThreads.Instance.addFun(new gif(5));
GifThreads.Instance.addFun(new gif(6));
GifThreads.Instance.addFun(new gif(7));

GifThreads.Instance.stopFun(0);
GifThreads.Instance.stopFun(1);
GifThreads.Instance.stopFun(2);
GifThreads.Instance.stopFun(3);
GifThreads.Instance.stopFun(4);

 备注:

1)由于需求改变,作者在项目中并没有实际用到这个自己写的工具类,代码仅做参考。

Leave a Reply

5 × 1 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据