线程工具类

自定义线程

package cm.soft.collect.threadUtil;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.LockSupport;

/**
 * 仿照线程池的形式封装一个线程处理 一个任务队列
 */
public class CustomThread extends Thread {
    private Queue<Runnable> unfinishedWorks = new LinkedBlockingDeque<>();// 未完成的任务
    private Runnable onceWork;// 一次性任务
    private Runnable oldOnceWork; // 老任务
    private Runnable cycleWork; // 循环任务,有循环任务最好不设置onceWork,因为cycleWork,会一直执行。
    private Runnable exeptionWork; // 异常任务
    private Runnable finallyWork;// 最终任务

    // 中断线程
    private volatile boolean interruptFlag = false;

    public void interrupt() {
        // LockSupport.unpark又会使处于wait的线程从等待队列中出去
        LockSupport.unpark(this);// 有可能线程在park(wait),要unpark
        interruptFlag = true;
        super.interrupt();
    }

    public CustomThread() {
        LockSupport.unpark(this);
    }

    public CustomThread(Runnable onceWork, Runnable cycleWork) {
        // LockSupport.unpark又会使处于wait的线程从等待队列中出去
        LockSupport.unpark(this);
        this.onceWork = onceWork;
        unfinishedWorks.add(onceWork);
        this.cycleWork = cycleWork;
    }

    public CustomThread(Runnable r) {
        super(r);
    }

    public void setOnceWork(Runnable onceWork) {
        // LockSupport.unpark又会使处于wait的线程从等待队列中出去
        LockSupport.unpark(this);
        this.onceWork = onceWork;
        unfinishedWorks.offer(onceWork);
    }

    public void setCycleWork(Runnable cycleWork) {
        LockSupport.unpark(this);
        this.cycleWork = cycleWork;
    }

    public void setExeptionWork(Runnable exeptionWork) {
        this.exeptionWork = exeptionWork;
    }

    public void setFinallyWork(Runnable finallyWork) {
        this.finallyWork = finallyWork;
    }

    private void setRunnableNull() {
        unfinishedWorks = null;
        onceWork = null;
        oldOnceWork = null;
        cycleWork = null;
    }

    public void run() {
        try {
            // 保证线程没有终止信号不终止
            while (!interruptFlag) {
                // 一次性的任务,只有新任务来的时候才执行
                if (onceWork != null && oldOnceWork != onceWork) {

                    onceWork.run();

                    if (unfinishedWorks != null && unfinishedWorks.contains(onceWork))
                        unfinishedWorks.remove(onceWork);
                    oldOnceWork = onceWork;
                } else if (unfinishedWorks != null && unfinishedWorks.size() > 0) {// 没有新任务,有未完成任务
                    for (Runnable unfinishedWork : unfinishedWorks) {
                        unfinishedWork.run();

                        if (unfinishedWorks != null && unfinishedWorks.contains(unfinishedWork))
                            unfinishedWorks.remove(unfinishedWork);
                    }
                } else if (cycleWork == null) {
                    LockSupport.park();// 减少不必要cpu消耗,防止线程一直在空载运行。使线程变成wait状态,进入等待队列
                }

                if (cycleWork != null)
                    cycleWork.run();
            }
        } catch (Exception e) {
            if (exeptionWork != null)
                exeptionWork.run();

        } finally {
            if (finallyWork != null)
                finallyWork.run();

            setRunnableNull();
        }
    }
}

自定义线程工厂

package cm.soft.collect.threadUtil;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;

/**
 * 自定义线程工厂 配合SingleThreadPerTask 根据者任务名获得一个专用线程 用于精细的控制
 */
public class CustomThreadFactory implements ThreadFactory {

    private static ConcurrentHashMap<String, Thread> threadMap = new ConcurrentHashMap<>();// 可以并发的读和写

    public static void addBizThread(String taskName) {
        Thread newThread = new CustomThread();
        newThread.setName(taskName);
        threadMap.put(taskName, newThread);
    }

    public static Thread getThread(Runnable runnable) {
        Thread newThread = new CustomThread(runnable);
        newThread.setDaemon(true);
        return newThread;
    }

    /**
     * 模仿单例写法,根据任务名获得一个专用线程,用于精细的控制。
     *
     * @param taskName
     * @return
     */
    public static Thread getThreadByBizName(String taskName) {
         Thread thread = threadMap.get(taskName);// 允许并发读取,不用加锁。而且读到的是最新的值

        if (thread == null || thread.getState().equals(Thread.State.TERMINATED)) {
            synchronized (CustomThreadFactory.class) {
                if (threadMap.get(taskName) == null || threadMap.get(taskName).getState().equals(Thread.State.TERMINATED)) {
                    addBizThread(taskName);// 线程死亡或者停止重新加一个线程,名字一样,使用时认为是一个线程
                    thread = threadMap.get(taskName);
                }
            }
        }

        if(thread!=null&&thread.getState().equals(Thread.State.NEW)){// 新的线程就启动
            thread.start();
        }

        return thread;
    }

    public Thread newThread(Runnable r){
        return getThread(r);
    }

}

自定义线程池工厂

package cm.soft.collect.threadUtil;

import cm.soft.collect.config.LogConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 自定义线程池工厂,获得线程池
 */
@Component
public class CustomThreadPoolFactory implements AutoCloseable {
    static volatile CustomThreadPoolFactory customThreadPoolFactory;

    @Autowired
    LogConfig log;

    private  ExecutorService boundedService; // 有界队列

    private  ExecutorService unboundedThreadService;// 无界线程池

    private  ExecutorService unboundedQueueService;// 无界任务队列

    private CustomThreadPoolFactory() {
    }

    public static CustomThreadPoolFactory getPoolFactory() {
        if (customThreadPoolFactory == null) {
            synchronized (CustomThreadPoolFactory.class) {
                if (customThreadPoolFactory == null) {
                    customThreadPoolFactory = new CustomThreadPoolFactory();
                }
            }
        }

        return customThreadPoolFactory;
    }

    public synchronized  ExecutorService getBoundedService() {
        if (boundedService == null) {
            boundedService = new ThreadPoolExecutor(5, 50, 30000,
                    TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5000));
        }

        return boundedService;
    }

    public synchronized  ExecutorService getUnboundedThreadService() {
        if (unboundedThreadService == null) {
            unboundedThreadService =
                    new ThreadPoolExecutor(5, 999, 30000,
                            TimeUnit.MILLISECONDS, new SynchronousQueue<>());// 无界的线程
        }

        return unboundedThreadService;
    }

    public synchronized ExecutorService getUnboundedQueueService() {

        if (unboundedQueueService == null) {
            unboundedQueueService =
                    new ThreadPoolExecutor(5, 5, 30000,
                            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());// 无界任务队列
        }

        return unboundedQueueService;
    }

    @Override
    @PreDestroy
    public void close() {
        if (boundedService != null && !boundedService.isShutdown()) {
            boundedService.shutdown();
            log.info("关闭有界线程池");
        }

        if (unboundedThreadService != null && !unboundedThreadService.isShutdown()) {
            unboundedThreadService.shutdown();
            log.info("关闭无界线程线程池");
        }

        if (unboundedQueueService != null && !unboundedQueueService.isShutdown()) {
            unboundedQueueService.shutdown();
            log.info("关闭无界队列线程池");
        }
    }
}

自定义请求

package cm.soft.collect.threadUtil;

import lombok.Data;

/**
 * 前端发出的请求
 * @param <T> 请求返回数据
 */
@Data
public class CustomRequestResponse<T> {
    private String line;
    private T t;
    private String topic;

    public synchronized void setT(T t){
        this.t=t;
        notifyAll();
    }

    public synchronized T getT(){
        if(t==null){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return t;
    }
}

自定义请求队列

package cm.soft.collect.threadUtil;


import java.util.LinkedList;
import java.util.Queue;

/**
 * 生产消费模式:请求队列
 */
public class CustomRequestQueue<T> {

    private Queue<T> requests = new LinkedList<>();

    private final Integer maxSize = 10000;

    // 实时数量
    private Integer size = 0;

    public synchronized T getRequest() {
        while (size <= 0) {

            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        size = size - 1;
        T customRequestResponse = requests.poll();
        notifyAll();
        return customRequestResponse;
    }

    public synchronized void addRequest(T customRequest) {
        if (size >= maxSize) {// 不会造成线程wait。
            return;
        }

        size = size + 1;
        requests.offer(customRequest);
        notifyAll();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值