线程模版总结

package com.wdk.logistics;

import com.wdk.ums.common.exception.BizException;
import com.wdk.ums.common.logger.UmsLogger;

import java.util.concurrent.CountDownLatch;

/**
 * 多线程执行类,无返回值 这里去掉了EagleEye
 */
public abstract class ShuttleRunable implements Runnable{


    private CountDownLatch keepLatch;

    private Long warehouseId;

    public void setWarehouseId(Long warehouseId) {
        this.warehouseId = warehouseId;
    }


    public void setKeepLatch(CountDownLatch keepLatch) {
        this.keepLatch = keepLatch;
    }

    /**
     * 执行runnable
     */
    protected abstract void execute();

    @Override
    public final void run() {
        try {
            // 执行任务
            execute();
            // 回调
            callback();
        } catch (BizException e) {
            UmsLogger.build().error(e.getMessage(), e);
            throw e;
        } catch (Throwable e) {
            UmsLogger.build().error("tenant.runnable.execute.error", e);
            throw e;
        } finally {
            if (keepLatch != null) {
                keepLatch.countDown();
            }
        }
    }

    /**
     * 执行完后的回调
     */
    protected void callback() {}

}

package com.wdk.logistics;

import com.wdk.ums.common.util.thread.LogisticsCallable;

import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ShuttleExecutor {

    private final ExecutorService executor;

    public ShuttleExecutor(String poolNamePrefix) {
        this(poolNamePrefix, Runtime.getRuntime().availableProcessors());
    }

    public ShuttleExecutor(String poolNamePrefix, int threadSize) {
        if (threadSize == 0) {
            executor = Executors.newCachedThreadPool(new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix));
        } else {
            executor = Executors.newFixedThreadPool(threadSize, new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix));
        }
    }

    public ShuttleExecutor(String poolNamePrefix, int threadSize, int queueSize) {
        executor = new ThreadPoolExecutor(threadSize, threadSize, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(queueSize), new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix));
    }

    public ShuttleExecutor(String poolNamePrefix, int threadSize, int maxThreadSize, int queueSize) {
        executor = new ThreadPoolExecutor(threadSize, maxThreadSize, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(queueSize), new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix));
    }

    public ShuttleExecutor(String poolNamePrefix, int threadSize, int maxThreadSize, long keepAliveTime, TimeUnit unit, int queueSize) {
        executor = new ThreadPoolExecutor(threadSize, maxThreadSize, keepAliveTime, unit, new LinkedBlockingDeque<>(queueSize), new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix));
    }

    public ShuttleExecutor(int threadSize, int maxThreadSize, long keepAliveTime, TimeUnit unit, int queueSize, ThreadFactory threadFactory) {
        executor = new ThreadPoolExecutor(threadSize, maxThreadSize, keepAliveTime, unit, new LinkedBlockingDeque<>(queueSize), threadFactory);
    }

    public ShuttleExecutor(String poolNamePrefix, int threadSize, int maxThreadSize, long keepAliveTime, TimeUnit unit, int queueSize, RejectedExecutionHandler handler) {
        executor = new ThreadPoolExecutor(threadSize, maxThreadSize, keepAliveTime, unit, new LinkedBlockingDeque<>(queueSize), new ShuttleExecutor.DefaultThreadFactory(poolNamePrefix), handler);
    }

    public ShuttleExecutor(int threadSize, int maxThreadSize, long keepAliveTime, TimeUnit unit, int queueSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        executor = new ThreadPoolExecutor(threadSize, maxThreadSize, keepAliveTime, unit, new LinkedBlockingDeque<>(queueSize), threadFactory, handler);
    }

    public void down() {
        shutdownAndAwaitTermination(this.executor);
    }

    private void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 提交单个任务,立即返回
     *
     * @param task
     */
    public void submit(ShuttleRunable task) {
        executor.submit(task);
    }

    /**
     * 提交单个异步处理任务。
     *
     * @param callable call
     * @return future
     */
    public <T> Future<T> submit(LogisticsCallable<T> callable) {
        return executor.submit(callable);
    }

    /**
     * 提交多个任务,并等待所有任务执行完毕才返回
     *
     * @param taskList 任务列表
     */
    public void submitAndWait(List<ShuttleRunable> taskList) throws InterruptedException {
        final CountDownLatch keep = new CountDownLatch(taskList.size());
        submitTaskList(taskList, keep);
        keep.await();
    }

    /**
     * 提交多个任务,并等待所有任务执行完毕才返回
     *
     * @param taskList       任务列表
     * @param timeoutSeconds 超时秒
     */
    public void submitAndWait(List<ShuttleRunable> taskList, Long timeoutSeconds) throws InterruptedException {
        final CountDownLatch keep = new CountDownLatch(taskList.size());
        submitTaskList(taskList, keep);
        keep.await(timeoutSeconds, TimeUnit.SECONDS);
    }

    /**
     * 提交多个任务,立即返回
     *
     * @param taskList
     */
    public void submit(List<ShuttleRunable> taskList) {
        for (ShuttleRunable task : taskList) {
            executor.submit(task);
        }
    }

    /**
     * 提交多个任务,等待所有任务执行完后才结束
     *
     * @param taskList 任务列表
     * @param keep     锁
     */
    private void submitTaskList(List<ShuttleRunable> taskList, CountDownLatch keep) {
        for (ShuttleRunable task : taskList) {
            task.setKeepLatch(keep);
            executor.submit(task);
        }
    }

    /**
     * 默认的线程工厂,初始化线程名前缀
     */
    public static class DefaultThreadFactory implements ThreadFactory {
        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        public DefaultThreadFactory(String prefix) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
            namePrefix = prefix + "-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }

}
package com.wdk.logistics;

public class ShuttleThreadConfig {
    public static ShuttleExecutor shuttleExecutor = new
        ShuttleExecutor("ProcessParamService", 10);
}


/**
 * 多穿上架仿真算法Job任务
 *
 * @author lierlin
 */
//DisallowConcurrentExecution 不开启多线程
@DisallowConcurrentExecution
@Slf4j
public class ShuttleInboundJob implements Job {


    private List<InventoryInfoModel> threadProcess() throws InterruptedException {
        Integer totalSize = inventoryInfoRepository.getTotalSize();
        int total;
        if (totalSize % Constant.PER_COUNT == 0) {
            total = totalSize / Constant.PER_COUNT;
        } else {
            total = totalSize / Constant.PER_COUNT + 1;
        }
        List<InventoryInfoModel> infoModels = Collections.synchronizedList(new ArrayList<>());
        List<ShuttleRunable> runnables = new ArrayList<>(total);
        for (int page = 1; page <= total; page++) {
            int finalPage = page;
            runnables.add(new ShuttleRunable() {
                @Override
                protected void execute() {
                    List<InventoryInfoModel> models = inventoryInfoRepository.queryByPage(finalPage, Constant.PER_COUNT);
                    infoModels.addAll(models);
                }
            });
        }
        ShuttleThreadConfig.shuttleExecutor.submitAndWait(runnables, 3L);
        return infoModels;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值