zoukankan      html  css  js  c++  java
  • java多线程实例

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * java 线程池实例
     * @author lixin
     */
    public class Test {
        public static void main(String[] args) {
            //采用固定大小线程池
            ExecutorService exe = Executors.newFixedThreadPool(2);
            //要处理的数据
            Map<String, String> map = new HashMap<String, String>();
            map.put("a", "aaaa");
            map.put("b", "bbbb");
            map.put("c", "cc");
            map.put("d", "d");
            map.put("e", "e");
            
            String m;
            int i = 0;
            for(Entry<String, String> entry: map.entrySet()) {
                m=entry.getValue();
                //调用线程池
                exe.execute(new MyThread(i,exe,m));
                i++;
            }    
        }
    }
    
    
    class MyThread implements Runnable
    {
        int id;
        ExecutorService exe;
        //m即实例对象
        String m = "";
        MyThread(int id, ExecutorService exe,String m) {
            this.exe = exe;
            this.id = id;
            this.m = m;
        }
        public void run() {
            //业务处理
            System.out.println("exe info:" + exe.toString()+"start");
            try {
                Thread.sleep(5000L);
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.println(id + "end");
        }
    }
  • 相关阅读:
    java截取字符串
    Integer
    Sql语句常用关键字
    mybatis三种传值方式
    mybatis中的#和$的区别
    374. Guess Number Higher or Lower
    278. First Bad Version
    69. Sqrt(x)
    35. Search Insert Position
    167. Two Sum II
  • 原文地址:https://www.cnblogs.com/lixin890808/p/5254712.html
Copyright © 2011-2022 走看看