Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / util / BaseThread.java
wangxitong on 6 Apr 2021 1 KB first commit
package com.smartdot.cgt.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Handler;
import android.os.Message;

public abstract class BaseThread extends Thread
{

	public static ExecutorService threadService;

	private static Object lock = new Object();

	public static ExecutorService getThreadService()
	{
		synchronized (lock)
		{
			if (threadService == null)
			{
				threadService = Executors.newCachedThreadPool();
			}
		}
		return threadService;
	}

	private boolean isThreadGoing = false;

	private Handler handler;

	public BaseThread(Handler handler)
	{
		this.handler = handler;
	}

	public boolean getIsThreadGoing()
	{
		return isThreadGoing;
	}

	@Override
	public void interrupt()
	{
		isThreadGoing = false;
		super.interrupt();
	}

	@Override
	public void run()
	{
		runThread();
		isThreadGoing = false;
	}

	public abstract void runThread();

	@Override
	public synchronized void start()
	{
		isThreadGoing = true;
		getThreadService().execute(this);
	}

	public Message obtainMessage()
	{
		Message msg = null;
		if (handler != null)
		{
			msg = handler.obtainMessage();
		}
		return msg;
	}

	public void sendMessage(Message msg)
	{
		if (handler != null && isThreadGoing)
		{
			handler.sendMessage(msg);
		}
	}

}