Java实现多任务执行助手

本文实例为大家分享了Java实现多任务执行助手的具体代码,供大家参考,具体内容如下

1.多线程执行任务类

package com.visy.threadpool;

import com.visy.executor.ExecutorFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ThreadPoolConfig {
    private TheadPoolProperties theadPoolProperties;
    private ThreadPoolExecutor executor;
    private ThreadPoolExecutor executorChild;

    public ThreadPoolConfig(TheadPoolProperties theadPoolProperties) {
        this.theadPoolProperties = theadPoolProperties;
        this.executor = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-service", theadPoolProperties.getQueueSize(), theadPoolProperties.getCoreThreadNum(), theadPoolProperties.getMaxPoolSize());
        this.executorChild = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-service-child", theadPoolProperties.getQueueSize(), theadPoolProperties.getCoreThreadNum(), theadPoolProperties.getMaxPoolSize());
    }

    public <V> List<V> doConcurrentTask(List<Callable<V>> taskList, ThreadPoolExecutor... executorChilds) {
        if (taskList != null && !taskList.isEmpty()) {
            List<V> resultList = new ArrayList();
            List futureList = null;

            try {
                if (this.executor.getQueue().size() >= this.theadPoolProperties.getQueueSize()) {
                    throw new RuntimeException("queue size bigger than 100, now size is " + this.executor.getQueue().size());
                }

                if (executorChilds != null && executorChilds.length > 0 && executorChilds[0] != null) {
                    futureList = executorChilds[0].invokeAll(taskList);
                } else {
                    futureList = this.executor.invokeAll(taskList, (long)this.theadPoolProperties.getTimeOut(), TimeUnit.SECONDS);
                }
            } catch (InterruptedException var6) {
                var6.printStackTrace();
            }

            this.doFutureList(resultList, futureList);
            return resultList;
        } else {
            return null;
        }
    }

    <V> void doFutureList(List<V> resultList, List<Future<V>> futureList) {
        if (futureList != null) {
            Iterator var3 = futureList.iterator();

            while(var3.hasNext()) {
                Future future = (Future)var3.next();

                try {
                    resultList.add(future.get());
                } catch (ExecutionException | InterruptedException var6) {
                    var6.printStackTrace();
                }
            }
        }

    }

    public <V> void doVoidConcurrentTask(List<Callable<V>> taskList) {
        if (taskList != null && !taskList.isEmpty()) {
            Iterator var2 = taskList.iterator();

            while(var2.hasNext()) {
                Callable<V> call = (Callable)var2.next();
                this.executor.submit(call);
            }

        }
    }

    public TheadPoolProperties getTheadPoolProperties() {
        return this.theadPoolProperties;
    }

    public ThreadPoolExecutor getExecutor() {
        return this.executor;
    }

    public ThreadPoolExecutor getExecutorChild() {
        return this.executorChild;
    }

    public void setTheadPoolProperties(TheadPoolProperties theadPoolProperties) {
        this.theadPoolProperties = theadPoolProperties;
    }

    public void setExecutor(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public void setExecutorChild(ThreadPoolExecutor executorChild) {
        this.executorChild = executorChild;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof ThreadPoolConfig)) {
            return false;
        } else {
            ThreadPoolConfig other = (ThreadPoolConfig)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label47: {
                    Object this$theadPoolProperties = this.getTheadPoolProperties();
                    Object other$theadPoolProperties = other.getTheadPoolProperties();
                    if (this$theadPoolProperties == null) {
                        if (other$theadPoolProperties == null) {
                            break label47;
                        }
                    } else if (this$theadPoolProperties.equals(other$theadPoolProperties)) {
                        break label47;
                    }

                    return false;
                }

                Object this$executor = this.getExecutor();
                Object other$executor = other.getExecutor();
                if (this$executor == null) {
                    if (other$executor != null) {
                        return false;
                    }
                } else if (!this$executor.equals(other$executor)) {
                    return false;
                }

                Object this$executorChild = this.getExecutorChild();
                Object other$executorChild = other.getExecutorChild();
                if (this$executorChild == null) {
                    if (other$executorChild != null) {
                        return false;
                    }
                } else if (!this$executorChild.equals(other$executorChild)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof ThreadPoolConfig;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $theadPoolProperties = this.getTheadPoolProperties();
        int result = result * 59 + ($theadPoolProperties == null ? 43 : $theadPoolProperties.hashCode());
        Object $executor = this.getExecutor();
        result = result * 59 + ($executor == null ? 43 : $executor.hashCode());
        Object $executorChild = this.getExecutorChild();
        result = result * 59 + ($executorChild == null ? 43 : $executorChild.hashCode());
        return result;
    }

    public String toString() {
        return "ThreadPoolConfig(theadPoolProperties=" + this.getTheadPoolProperties() + ", executor=" + this.getExecutor() + ", executorChild=" + this.getExecutorChild() + ")";
    }
}

2.执行器工厂类

package com.visy.executor;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExecutorFactory {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorFactory.class);
    private static final Map<String, ThreadPoolExecutor> threadPoolExecutorMap = new ConcurrentHashMap();
    private static final int DEFAULT_QUEUE_SIZE = 1000;
    private static final String DEFAULT_EXECUTOR_NAME = "default-executor";
    private static final int MAX_THREAD_NUM = 100;
    private static final int CORE_THREAD_NUM = 1;
    private static volatile ExecutorFactory instance;

    private ExecutorFactory() {
    }

    public static ExecutorFactory getInstance() {
        if (instance == null) {
            Class var0 = ExecutorFactory.class;
            synchronized(ExecutorFactory.class) {
                if (instance == null) {
                    instance = new ExecutorFactory();
                }
            }
        }

        return instance;
    }

    public ThreadPoolExecutor getThreadPoolExecutorByName(String name) {
        return (ThreadPoolExecutor)threadPoolExecutorMap.get(name);
    }

    public static Map<String, ThreadPoolExecutor> getThreadPoolExecutorMap() {
        return threadPoolExecutorMap;
    }

    public ThreadPoolExecutor getThreadPoolExecutor(String threadPoolExecutorName, int queueSize, int coreThreadNum, int maxPoolSize) {
        if (StringUtils.isBlank(threadPoolExecutorName)) {
            throw new IllegalArgumentException("thread name empty");
        } else {
            if (!threadPoolExecutorMap.containsKey(threadPoolExecutorName)) {
                Class var5 = ExecutorFactory.class;
                synchronized(ExecutorFactory.class) {
                    if (!threadPoolExecutorMap.containsKey(threadPoolExecutorName)) {
                        ThreadPoolExecutor executor = (new ThreadPool(coreThreadNum, maxPoolSize, 30L, queueSize, threadPoolExecutorName)).getExecutor();
                        threadPoolExecutorMap.put(threadPoolExecutorName, executor);
                        logger.info("thread name: {} executor created", threadPoolExecutorName);
                    }
                }
            }

            return (ThreadPoolExecutor)threadPoolExecutorMap.get(threadPoolExecutorName);
        }
    }

    public <T extends Runnable> void submit(T t) {
        ThreadPoolExecutor defaultExecutor = this.getThreadPoolExecutor();
        defaultExecutor.submit(t);
    }

    public <T extends Runnable> void submit(String poolName, T t) {
        ThreadPoolExecutor executor = this.getThreadPoolExecutorByName(poolName);
        if (executor == null) {
            logger.error("thread name: {} executor not exist.", poolName);
            throw new IllegalArgumentException("thread name:" + poolName + " executor not exist.");
        } else {
            executor.submit(t);
        }
    }

    public <T extends Callable<Object>> Future<Object> submit(T t) {
        ThreadPoolExecutor defaultExecutor = this.getThreadPoolExecutor();
        return defaultExecutor.submit(t);
    }

    public <T extends Callable<Object>> Future<Object> submit(String poolName, T t) {
        ThreadPoolExecutor executor = this.getThreadPoolExecutorByName(poolName);
        if (executor == null) {
            logger.error("thread poolName: {} executor not exist.", poolName);
            throw new IllegalArgumentException("thread poolName:" + poolName + " executor not exist.");
        } else {
            return executor.submit(t);
        }
    }

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return this.getThreadPoolExecutor("default-executor", 1000, 1, 100);
    }
}

3.多线程配置类

package com.visy.threadpool;

import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;

@Validated
@Configuration
@ConfigurationProperties(prefix = "visy.threadpool")
public class TheadPoolProperties {
    // 执行并行任务时,等待多久时间超时(单位:秒)
    @NotNull
    private Integer timeOut;
    // 队列大小
    @NotNull
    private Integer queueSize; 
    // 核心线程数量
    @NotNull
    private Integer coreThreadNum;
    // 线程池最大线程数量
    @NotNull
    private Integer maxPoolSize;
    // 并行执行每组大小
    private Integer groupSize = 20;

    public TheadPoolProperties() {
    }

    public Integer getTimeOut() {
        return this.timeOut;
    }

    public Integer getQueueSize() {
        return this.queueSize;
    }

    public Integer getCoreThreadNum() {
        return this.coreThreadNum;
    }

    public Integer getMaxPoolSize() {
        return this.maxPoolSize;
    }

    public Integer getGroupSize() {
        return this.groupSize;
    }

    public void setTimeOut(Integer timeOut) {
        this.timeOut = timeOut;
    }

    public void setQueueSize(Integer queueSize) {
        this.queueSize = queueSize;
    }

    public void setCoreThreadNum(Integer coreThreadNum) {
        this.coreThreadNum = coreThreadNum;
    }

    public void setMaxPoolSize(Integer maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public void setGroupSize(Integer groupSize) {
        this.groupSize = groupSize;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof TheadPoolProperties)) {
            return false;
        } else {
            TheadPoolProperties other = (TheadPoolProperties)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label71: {
                    Object this$timeOut = this.getTimeOut();
                    Object other$timeOut = other.getTimeOut();
                    if (this$timeOut == null) {
                        if (other$timeOut == null) {
                            break label71;
                        }
                    } else if (this$timeOut.equals(other$timeOut)) {
                        break label71;
                    }

                    return false;
                }

                Object this$queueSize = this.getQueueSize();
                Object other$queueSize = other.getQueueSize();
                if (this$queueSize == null) {
                    if (other$queueSize != null) {
                        return false;
                    }
                } else if (!this$queueSize.equals(other$queueSize)) {
                    return false;
                }

                label57: {
                    Object this$coreThreadNum = this.getCoreThreadNum();
                    Object other$coreThreadNum = other.getCoreThreadNum();
                    if (this$coreThreadNum == null) {
                        if (other$coreThreadNum == null) {
                            break label57;
                        }
                    } else if (this$coreThreadNum.equals(other$coreThreadNum)) {
                        break label57;
                    }

                    return false;
                }

                Object this$maxPoolSize = this.getMaxPoolSize();
                Object other$maxPoolSize = other.getMaxPoolSize();
                if (this$maxPoolSize == null) {
                    if (other$maxPoolSize != null) {
                        return false;
                    }
                } else if (!this$maxPoolSize.equals(other$maxPoolSize)) {
                    return false;
                }

                Object this$groupSize = this.getGroupSize();
                Object other$groupSize = other.getGroupSize();
                if (this$groupSize == null) {
                    if (other$groupSize == null) {
                        return true;
                    }
                } else if (this$groupSize.equals(other$groupSize)) {
                    return true;
                }

                return false;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof TheadPoolProperties;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $timeOut = this.getTimeOut();
        int result = result * 59 + ($timeOut == null ? 43 : $timeOut.hashCode());
        Object $queueSize = this.getQueueSize();
        result = result * 59 + ($queueSize == null ? 43 : $queueSize.hashCode());
        Object $coreThreadNum = this.getCoreThreadNum();
        result = result * 59 + ($coreThreadNum == null ? 43 : $coreThreadNum.hashCode());
        Object $maxPoolSize = this.getMaxPoolSize();
        result = result * 59 + ($maxPoolSize == null ? 43 : $maxPoolSize.hashCode());
        Object $groupSize = this.getGroupSize();
        result = result * 59 + ($groupSize == null ? 43 : $groupSize.hashCode());
        return result;
    }

    public String toString() {
        return "TheadPoolProperties(timeOut=" + this.getTimeOut() + ", queueSize=" + this.getQueueSize() + ", coreThreadNum=" + this.getCoreThreadNum() + ", maxPoolSize=" + this.getMaxPoolSize() + ", groupSize=" + this.getGroupSize() + ")";
    }
}

4.列表拆分工具类

package com.visy.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.jar.Attributes;

/**
 * 列表或数组按指定大小分组,用于批量取一部分数据循环处理
 *
 */
public class ArraySplitUtil<T> {
    /**
     * 按指定大小对列表分组
     * @param list
     * @param splitSize
     * @return
     */
    public List<List<T>> splistList(List<T> list, int splitSize) {
        if (null == list || list.size() == 0) {
            return null;
        }
        int listSize = list.size();
        List<List<T>> newList = new ArrayList<>();
        if (listSize < splitSize) {
            newList.add(list);
            return newList;
        }
        int addLength = splitSize;
        int times = listSize / splitSize;
        if (listSize % splitSize != 0) {
            times += 1;
        }
        int start = 0;
        int end = 0;
        int last = times - 1;
        for (int i = 0; i < times; i++) {
            start = i * splitSize;
            if (i < last) {
                end = start + addLength;
            } else {
                end = listSize;
            }
            newList.add(list.subList(start, end));
        }
        return newList;
    }

    /**
     * 按指定大小对数组分组
     * @param array
     * @param splitSize
     * @return
     */
    public List<T[]> splistArray(T[] array, int splitSize) {
        if (null == array) {
            return null;
        }
        int listSize = array.length;
        List<T[]> newList = new ArrayList<>();
        if (listSize < splitSize) {
            newList.add(array);
            return newList;
        }
        int addLength = splitSize;
        int times = listSize / splitSize;
        if (listSize % splitSize != 0) {
            times += 1;
        }
        int start = 0;
        int end = 0;
        int last = times - 1;
        for (int i = 0; i < times; i++) {
            start = i * splitSize;
            if (i < last) {
                end = start + addLength;
            } else {
                end = listSize;
            }
            newList.add(Arrays.copyOfRange(array, start, end));
        }
        return newList;
    }

    public static <E> ArraySplitUtil<E> build(){
        return new ArraySplitUtil<>();
    }
}

5.多任务执行助手类

package com.visy.helper;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.visy.utils.ArraySplitUtil;
import com.visy.threadpool.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 多任务助手
 * @author visy.wang
 * @date 2022/5/9 14:38
 */
@Service
public class MultiTaskHelper {
    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    private static final Map<String,ArraySplitUtil<?>> ArraySplitUtilCache = new ConcurrentHashMap<>();

    public <I,O> List<List<O>> createAndRunListTask(List<I> list, Function<I,O> handler){
        return createAndRunListTask(list, null, handler);
    }

    public <I,O> List<List<O>> createAndRunListTaskV2(List<I> list, Function<List<I>, List<O>> handler){
        return createAndRunListTask(list, handler, null);
    }

    public <I> void createAndRunListTaskWithoutReturn(List<I> list, Consumer<I> handler){
        createAndRunListTaskWithoutReturn(list, null, handler);
    }

    public <I> void createAndRunListTaskWithoutReturnV2(List<I> list, Consumer<List<I>> handler){
        createAndRunListTaskWithoutReturn(list, handler, null);
    }

    /**
     * 把列表按线程数分组
     * @param list 列表
     * @return 分组后的列表
     */
    @SuppressWarnings("unchecked")
    private <T> List<List<T>> listSplit(List<T> list){
        String key = list.get(0).getClass().getName();
        int groupSize = threadPoolConfig.getTheadPoolProperties().getGroupSize();
        ArraySplitUtil<T> arraySplitUtil = (ArraySplitUtil<T>)ArraySplitUtilCache.get(key);
        if(Objects.isNull(arraySplitUtil)){
            arraySplitUtil = ArraySplitUtil.build();
            ArraySplitUtilCache.put(key, arraySplitUtil);
        }
        return arraySplitUtil.splistList(list, groupSize);
    }

    /**
     * 创建并运行多任务
     * @param list 输入数据列表
     * @param handler1 处理器1 (优先级使用)
     * @param handler2 处理器2
     * @param <I> 输入数据类型
     * @param <O> 输出数据类型
     * @return 执行结果分组列表
     */
    private <I,O> List<List<O>> createAndRunListTask(List<I> list,  Function<List<I>, List<O>> handler1, Function<I,O> handler2){
        List<List<I>> listGroup = listSplit(list);
        //设定每个组的任务
        List<Callable<List<O>>> taskList = Lists.newArrayListWithExpectedSize(listGroup.size());
        listGroup.stream().filter(CollectionUtils::isNotEmpty).forEach(subList -> {
            taskList.add(() -> {
                if(Objects.nonNull(handler1)){
                    return handler1.apply(subList);
                }else if(Objects.nonNull(handler2)){
                    return subList.stream().map(handler2).collect(Collectors.toList());
                }else{
                    return null;
                }
            });
        });
        return threadPoolConfig.doConcurrentTask(taskList);
    }

    /**
     * 创建并运行多任务(无返回结果)
     * @param list 输入数据列表
     * @param handler1 处理器1 (优先级更高)
     * @param handler2 处理器2
     * @param <I> 输入数据类型
     */
    private <I> void createAndRunListTaskWithoutReturn(List<I> list, Consumer<List<I>> handler1, Consumer<I> handler2){
        List<List<I>> listGroup = listSplit(list);
        //设定每个组的任务
        List<Callable<List<?>>> taskList = Lists.newArrayListWithExpectedSize(listGroup.size());
        listGroup.stream().filter(CollectionUtils::isNotEmpty).forEach(subList -> {
            taskList.add(() -> {
                if(Objects.nonNull(handler1)){
                    handler1.accept(subList);
                }else if(Objects.nonNull(handler2)){
                    subList.forEach(handler2);
                }
                return null;
            });
        });
        threadPoolConfig.doConcurrentTask(taskList);
    }
}

6.多任务助手使用:

@Autowired
package com.zoom.fleet.schedule.service;

import com.visy.helper.MultiTaskHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 多任务助手使用示例
 * @author visy.wang
 * @date 2022/5/13 14:11
 */
@Service
public class MultiTaskTest {
    @Autowired
    private MultiTaskHelper multiTaskHelper;

    private void test(){

        //待多任务执行的数据列表
        List<String> idList = new ArrayList<>();

        //1.有返回结果的执行方式一, 定义单个数据的处理逻辑,返回多任务执行结果和合集
        List<List<Long>> resultList = multiTaskHelper.createAndRunListTask(idList, id->{
            //每一项数据的业务代码
            return Long.valueOf(id);
        });

        //2.有返回结果的执行方式二, 定义单个数线程的处理逻辑,返回多任务执行结果和合集
        resultList = multiTaskHelper.createAndRunListTaskV2(idList, subIdList->{
            //每一个线程下列表操作的业务代码
            return subIdList.stream().map(id->{
                //每一项数据的业务代码
                return Long.valueOf(id);
            }).collect(Collectors.toList());
        });

        //3.无返回结果的执行方式一, 定义单个数据的处理逻辑
        multiTaskHelper.createAndRunListTaskWithoutReturn(idList, id->{
            //每一项数据的业务代码...
        });

        //3.无返回结果的执行方式一, 定义单个数据的处理逻辑
        multiTaskHelper.createAndRunListTaskWithoutReturnV2(idList, subIdList->{
            subIdList.forEach(id->{
                //每一项数据的业务代码...
            });
            //继续操作subIdList...
        });
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Java 使用线程池执行多个任务的示例

    在执行一系列带有IO操作(例如下载文件),且互不相关的异步任务时,采用多线程可以很极大的提高运行效率.线程池包含了一系列的线程,并且可以管理这些线程.例如:创建线程,销毁线程等.本文将介绍如何使用Java中的线程池执行任务. 1 任务类型 在使用线程池执行任务之前,我们弄清楚什么任务可以被线程池调用.按照任务是否有返回值可以将任务分为两种,分别是实现Runnable的任务类(无参数无返回值)和实现Callable接口的任务类(无参数有返回值).在打代码时根据需求选择对应的任务类型. 1.1 实现

  • 详解Java ES多节点任务的高效分发与收集实现

    目录 一.概述 二.请求分发的简单思路 三.es中search的多节点分发收集 3.1.多节点响应结果处理 3.2.异步提交请求实现 一.概述 我们知道,当我们对es发起search请求或其他操作时,往往都是随机选择一个coordinator发起请求.而这请求,可能是该节点能处理,也可能是该节点不能处理的,也可能是需要多节点共同处理的,可以说是情况比较复杂. 所以,coordinator的重要工作是,做请求分发与结果收集.那么,如何高性能和安全准确地实现这一功能则至关重要. 二.请求分发的简单思

  • Java实现多任务执行助手

    本文实例为大家分享了Java实现多任务执行助手的具体代码,供大家参考,具体内容如下 1.多线程执行任务类 package com.visy.threadpool; import com.visy.executor.ExecutorFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import jav

  • java finally块执行时机全面分析

    java里 finally 关键字通常与try catch块一起使用.用来在方法结束前或发生异常时做一些资源释放的操作.最近也看到网上有一些讨论try catch finally关键词执行的顺序的文章,并给出了finally块是在方法最后执行的. 这些观点普遍认为: 1) finally关键词是在程序return语句后返回上一级方法前执行的,其中返回值会保存在一个临时区域,待执行完finally块的部分后,在将临时区域的值返回. 2) 若finally块里有返回值会替换掉程序中前面的try 或c

  • Java 多线程有序执行的几种方法总结

    Java 多线程有序执行的几种方法总结 同事无意间提出了这个问题,亲自实践了两种方法.当然肯定还会有更多更好的方法. 方法一 import java.util.concurrent.atomic.AtomicInteger; public class OrderedThread1 { static AtomicInteger count = new AtomicInteger(0); public static void main(String[] args) throws Interrupte

  • Eclipse 导出可执行Java工程/可执行Jar文件(包含第三方Jar包)

    Eclipse导出可执行Java工程/可执行Jar文件(包含第三方Jar包) 师兄部署了新的虚拟机,新学期大搞起来!之前由于爬虫代码不稳定,所以一直都是直接用Eclipse运行,然后遇到问题就修改的.但是这个比较麻烦,而且Eclipse本身就很占内存啊,摔!所以今天下午就把之前的代码清减了一下,对很多挫挫的System.out.println替换了log4j,路径啊数据库连接呀用配置文件处理了,最后打成可执行的Jar,这样在新的虚机上就可以大展拳脚咯^_^Y Biu~废话说完,进入正题,将Jav

  • Java动态编译执行代码示例

    在某些情况下,我们需要动态生成java代码,通过动态编译,然后执行代码.JAVAAPI提供了相应的工具(JavaCompiler)来实现动态编译.下面我们通过一个简单的例子介绍,如何通过JavaCompiler实现java代码动态编译. 一.获取JavaCompiler JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 获取JDK提供的java编译器,如果没有提供编译器,则返回null: 二.编译 //获取java文件管理

  • Java实现的执行python脚本工具类示例【使用jython.jar】

    本文实例讲述了Java实现的执行python脚本工具类.分享给大家供大家参考,具体如下: 这里java中执行python脚本工具类,需要使用jython.jar java中执行python脚本工具类,学习的时候写着玩: import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; i

  • 对java for 循环执行顺序的详解

    如下所示: for(表达式1;表达式2;表达式3) { //循环体 } 先执行"表达式1",再进行"表达式2"的判断,判断为真则执行 "循环体",循环体执行完以后执行表达式3. 例如 for(int i=0;i<2;i++){ //TODO } 先执行 int i = 0; 然后 判断 i<2 然后执行函数体 最后执行i++ 然后轮回到判断i<2 int[] arr = new int[3]; int j; arr[0] = 1

  • java多线程中执行多个程序的实例分析

    我们知道多线程因为同时处理子线程的能力,对于程序运行来说,能够达到很高的效率.不过很多人对于多线程的执行方法还没有尝试过,本篇我们将为大家介绍创建线程的方法,在这个基础上,对程序执行多条命令的方法进行展示.下面我们就来看看具体的操作步骤吧. 1.创建线程对象我们需要用到Thread类,该类是java.lang包下的一个类,所以调用时不需要导入包.下面我们先创建一个新的子类来继承Thread类,然后通过重写run()方法(将需要同时进行的任务写进run()方法内),来达到让程序同时做多件事情的目的

  • 详解Java的编译执行与解释执行

    一.前言 编程语言分为低级语言和高级语言,机器语言.汇编语言是低级语言,C.C++.java.python等是高级语言. 机器语言是最底层的语言,能够直接执行.而我们编写的源代码是人类语言,计算机只能识别某些特定的二进制指令,在程序真正运行之前必须将源代码转换成二进制指令.汇编语言通过汇编器翻译成机器指令后执行,一条汇编指令,对应着一条机器指令. 高级语言编程的程序有三种执行方式: 1.一种是编译执行,源程序先通过编译器(负责将源程序翻译成目标机器指令)翻译成机器指令,通过编译-->链接-->

  • Java类初始化执行流程解析

    测试代码: package com.test.ClassLaoderTest; public class test1 { public static String s_variable = "静态变量"; public String init_variable = "公开的变量"; private String p_variable = "私有的变量"; //静态代码块 static { System.out.println(s_variable

随机推荐