简单的线程实现Thread

Thread是通过实现run()方法,然后运行start来启动线程,
现简单的包装Thread来实现配置线程
一、CommonTHD 类,其中有工具类可以自行替换
package xu.thread;

import org.apache.log4j.Logger;
import xu.tools.TimeTools;
import java.util.Properties;

/**
 * ******************************************************************************
 * <p>Filename    : CommonTHD
 * <p>Description : 通用线程定义
 * ******************************************************************************
 **/

public abstract class CommonTHD extends Thread{
    /**
     * 线程启停时间
     */
    protected String startOrStopTime="";

    /**
     * 退出标志
     */
    protected boolean isExit = false;

    /**
     * 睡眠时间 单位:毫秒
     */
    protected int sleepTime = 60000;

    /**
     * 线程标识名
     */
    protected String threadName = "";

    /**
     * 线程名
     */
    protected String className = "";

    /**
     * 线程的个数
     */
    protected int threadCount = 1;
    /**
     * 线程号
     */
    protected int threadNum = 0;

    protected static Properties props = null;

    static {
        try {
            props = new Properties();
            props.load(CommonTHD.class.getClassLoader().getResourceAsStream("threadconfig.properties"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    Logger logger = Logger.getLogger(getClass());

    /**
     * 构造函数
     */
    public CommonTHD() {
        init();
    }

    public boolean getIsExit() {
        return isExit;
    }

    public void setIsExit(boolean isExit) {
        setStartOrStopTime(TimeTools.getCurrentTime());
        this.isExit = isExit;
        if(isExit){
            synchronized(this){
                this.notifyAll();
            }
        }
    }

    public int getSleepTime() {
        return this.sleepTime;
    }

    public String getThreadName() {
        return threadName;
    }

    public String getClassName() {
        return className;
    }

    public int getThreadCount() {
        return threadCount;
    }

    public void setSleepTime(int sleepTime) {
        this.sleepTime = sleepTime;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public void setThreadCount(int threadCount) {
        this.threadCount = threadCount;
    }

    public int getThreadNum() {
        return threadNum;
    }

    public void setThreadNum(int threadNum) {
        this.threadNum = threadNum;
    }

    /**
     * 初始化
     */
    private void init() {
        try {
            String value = null;
            className = this.getClass().getSimpleName();

            value = props.getProperty(className+".SleepTime");
            if (value != null) {
                sleepTime = Integer.parseInt(value);
            }

            value = props.getProperty(className+".ThreadCount");
            if (value != null) {
                threadCount = Integer.parseInt(value);
            }

            threadName=getClass().getSimpleName();
        }catch (Exception e){
            logger.error("初始化失败:" + e);
        }
    }

    public void run() {
        try{
            setStartOrStopTime(TimeTools.getCurrentTime("yyyy-MM-dd HH:mm:ss"));

            try{
                operationOnStart();
            }catch (Exception ex2){
                logger.error("[" + className + "] 线程启动前出现未知异常-忽略.", ex2);
            }

            while (!isExit){
                try{
                    runWork();
                }catch (Exception ex)    {
                    logger.error("[" + className + "] 线程处理过程中出现异常-忽略", ex);
                }

                if (!isExit){
                    waitSleepTime();
                }
            }

            try{
                operationOnExit();
            }catch (Exception ex3){
                logger.error("[" + className + "] 线程退出过程出现未知异常-忽略", ex3);
            }

        }finally{

        }
    }

    public void waitSleepTime(){
        synchronized(this){
            try{this.wait(sleepTime);}catch(Exception e){}
        }
    }

    private void operationOnExit() {
        doOnExit();
        logger.info("[thread end] "+toString());
    }

    private void operationOnStart() {
        logger.info("[thread start] "+toString());
        doOnStart();
    }

    public abstract void doOnStart();

    public abstract void doOnExit();

    public abstract void runWork();

    public boolean isStop(){
        return !isAlive();
    }

    public String getStartOrStopTime() {
        return startOrStopTime;
    }

    /**
     * 设置线程启停时间
     * @param startOrStopTime
     */
    public void setStartOrStopTime(String startOrStopTime) {
        this.startOrStopTime = startOrStopTime;
    }


    public String toString() {
        return "["+threadName+"]"+" sleepTime=" + sleepTime+ ",threadCount=" + threadCount;
    }
}

二、MULTIDoJobThd类

package xu.thread;

public class MULTIDoJobThd extends CommonTHD {
    public MULTIDoJobThd() {
    }

    /**
     * 线程工作的处理器
     */
    private ThdProcess thdProcessor = null;

    public void runWork() {
        if (thdProcessor == null)
        {
            logger.info("[" + className + "] 线程处理器没有设置");
        }

        try
        {
                thdProcessor.process();

        }
        catch (Exception ex)
        {
            logger.info("[" + className + "] 处理过程出现异常.", ex);
        }
    }

    public void doOnExit() {
    }

    public void doOnStart() {
    }

    public ThdProcess getThdProcessor() {
        return thdProcessor;
    }

    public void setThdProcessor(ThdProcess thdProcessor) {
        this.thdProcessor = thdProcessor;
    }
}

三、ThdProcess类

package xu.thread;

public class  ThdProcess {

    private MULTIDoJobThd multiIDoJobThd = null;

    public MULTIDoJobThd getMultiIDoJobThd() {
        return multiIDoJobThd;
    }

    public void setMultiIDoJobThd(MULTIDoJobThd multiIDoJobThd) {
        this.multiIDoJobThd = multiIDoJobThd;
    }

    public void process() throws Exception{

    }

    public void initLog(){

    }
}

四、实现自己的需要运行的 WorkThd类和 WorkProcess类

package xu.thread.main;

import org.apache.log4j.Logger;
import xu.thread.ThdProcess;
import xu.tools.ThreadLogger;

public class WorkProcess extends ThdProcess {
    Logger logger = null;

    public void initLog(){
        logger = ThreadLogger.getLogger(getMultiIDoJobThd().getThreadName());
    }

    public void process() throws Exception {
        logger.info("跑线程" + getMultiIDoJobThd().getThreadName());
    }
}
package xu.thread.main;

import xu.thread.MULTIDoJobThd;

public class WorkThd extends MULTIDoJobThd {
    public WorkThd() {
        WorkProcess workProcess=new WorkProcess();
        workProcess.setMultiIDoJobThd(this);
        setThdProcessor(workProcess);
    }
}

五、配置好 threadconfig.properties文件。实现CommonControlThd和main类

threadconfig.properties文件内容

WorkThd.SleepTime=2000
WorkThd.ThreadCount=5

CommonControlThd.ChildThdList=WorkThd
CommonControlThd.File=xu.thread.main
package xu.thread;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Properties;

public class CommonControlThd {
    /**
     * 子线程列表
     */
    public ArrayList<MULTIDoJobThd> childThdList = new ArrayList<MULTIDoJobThd>();

    Logger logger = Logger.getLogger(getClass());

    protected static Properties props = null;

    protected String className = this.getClass().getSimpleName();

    static {
        try {
            props = new Properties();
            props.load(CommonControlThd.class.getClassLoader().getResourceAsStream("threadconfig.properties"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    public CommonControlThd() {
    }

    /**
     * 初始化并且启动所有的线程
     */
    protected void initChildThd() {
        String[] childThdClassNames = null;
        try {
            childThdClassNames = props.getProperty(className + ".ChildThdList").split("\\.");
        }catch (Exception ex){
            logger.error("[" + className + "] 检查ChildThdList配置->" , ex);
        }

        for (int i = 0; i < childThdClassNames.length; i++) {
            int currentThdCount = 0;
            String s = props.getProperty(childThdClassNames[i] + ".ThreadCount");
            try {
                currentThdCount = Integer.parseInt(s);
            } catch (Exception ex) {
                logger.error("[" + className + "] 线程获取处理线程个数出错", ex);
            }

            try {
                //创建线程
                MULTIDoJobThd thd = null;
                for (int j = 0; j < currentThdCount; j++) {
                    thd = (MULTIDoJobThd) Class.forName(props.getProperty("CommonControlThd.File")+"."+childThdClassNames[i]).newInstance();
                    thd.setThreadName(thd.getThreadName() + "_" + j);
                    thd.getThdProcessor().initLog();
                    childThdList.add(thd);
                    thd.start();
                }
            } catch (Exception ex1) {
                logger.error("[" + className + "] 启动子线程出错->" + childThdClassNames[i], ex1);
            }

        }
    }

    /**
     * 停止所有的线程
     */
    protected void stopChildThd() {
        MULTIDoJobThd thd = null;
        for (int i = 0; i < childThdList.size(); i++) {
            thd = (MULTIDoJobThd) childThdList.get(i);
            thd.setIsExit(true);
        }
    }

    /**
     * 停止一组线程
     * param jobThds MULTIDoJobThd[]
     */
    public void stopThds(MULTIDoJobThd[] Thds) {
        if (Thds == null) {
            return;
        }
        for (int i = 0; i < Thds.length; i++) {
            if (Thds[i] != null) {
                Thds[i].setIsExit(true);
            }
        }
    }

    public void doStart() {
        initChildThd();
    }

    public void doExit() {
        stopChildThd();
    }
}
package xu.thread.main;


import org.apache.log4j.Logger;
import xu.thread.CommonControlThd;

public class main {
    public static void main(String[] arg0) throws Exception {

        CommonControlThd commonControlThd = new CommonControlThd();
        commonControlThd.doStart();
    }

}

 

posted @ 2020-12-10 17:35  xujf  Views(213)  Comments(0Edit  收藏  举报