多线程

来源:互联网 发布:网络流行关键词 编辑:程序博客网 时间:2024/06/14 01:05
package test;import java.util.concurrent.*;import java.util.Date;import java.util.HashSet;import java.util.List;import java.util.Set;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;public class ExecuService {    public static void main(String[] args) throws ExecutionException, InterruptedException {        System.out.println("----程序开始运行----");        Date date1 = new Date();        int taskSize = 5;        // 创建一个线程池        ExecutorService pool = Executors.newFixedThreadPool(taskSize);        // 创建多个有返回值的任务        List<Future> list = new ArrayList<Future>();        Set<String> protlist = new HashSet<String>();        File file = new File("config");        String test[];        test = file.list();        for (int i = 0; i < test.length; i++) {            System.out.println(test[i]);        }        for (int i = 0; i < taskSize; i++) {            Callable c = new MyCallable(" ");            // 执行任务并获取Future对象            Future f = pool.submit(c);            System.out.println(">>>" + f.get().toString());        }        // 关闭线程池        pool.shutdown();        // 获取所有并发任务的运行结果        for (Future f : list) {            // 从Future对象上获取任务的返回值,并输出到控制台            System.out.println(">>>" + f.get().toString());        }        Date date2 = new Date();        System.out.println("----程序结束运行----,程序运行时间【" + (date2.getTime() - date1.getTime()) + "毫秒】");    }}class MyCallable implements Callable<Object> {    private String path;    MyCallable(String path) {        this.path = path;    }    StringBuffer getRun(String dir, String command) {        StringBuffer stringBuffer = new StringBuffer();        try {            Process process = Runtime.getRuntime().exec(dir + " " + command);            System.out.println("please wait ...");            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));            String line = null;            while ((line = reader.readLine()) != null) {                stringBuffer.append(line + "\n");            }        }        catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return stringBuffer;    }    public Object call() throws Exception {        System.out.println(">>>" + path + "任务启动");        Date dateTmp1 = new Date();        // getRun("C:\\Program Files (x86)\\Nmap\\nmap.exe",        // "-sn --open -iL " + path + " -oX config/"+path+".xml");        Date dateTmp2 = new Date();        long time = dateTmp2.getTime() - dateTmp1.getTime();        System.out.println(">>>" + path + "任务终止");        return path + "任务返回运行结果,当前任务时间【" + time + "毫秒】";    }}
0 0
原创粉丝点击