线程池(四):手写线程池实战

一、线程池实战例子

项目背景:需要查出一百个用户的信息,并且给他们的邮箱发送邮件,打印出最终结果

用户类

public class User {
    private Integer id;
    private String email;

    public User(Integer id, String email) {
        this.id =id;
        this.email =email;
    }

    public String getEmail() {
        return email;
    }
}

任务类

public class Task implements Callable {
   private Integer id;

    public Task(Integer id) {
        this.id = id;
    }

    @Override
    public String call() throws Exception {
        //调用业务方提供的查user的服务,id不同,创建任务的时候就传过来id
        User user = DoSomethingService.queryUser(this.id);
        //调用业务方提供发送邮件的服务,email不同
        String result = DoSomethingService.sendUserEmail(user.getEmail());
        return result;
    }
}

提供的服务类

//业务提供的服务
public  class DoSomethingService {
    //查询用户100ms
     public static  User queryUser(Integer id) throws InterruptedException {
         //这里可以调用查询user的sql语句
         Thread.sleep(100);
         User u= new User(id,id+"xhJaver.com");
         return u;
     }

     //发送邮件50ms
    public static String sendUserEmail(String email) throws InterruptedException {
        if (email!=null){
            //这里可以调用发送email的语句
            Thread.sleep(50);
            return "发送成功"+email;
        }else {
            return "发送失败";
        }

    }
}

我们再来比较一下单线程情况下和多线程情况下相同的操作差别有多大

public class SingleVSConcurrent {
    public static void main(String[] args) {
     //我们模拟一百个用户,我们查出来这一百个用户然后再给他们发邮件
        long singleStart = System.currentTimeMillis();
        for (int i=0;i<100;i++){
            User user = null;
            try {
                user = DoSomethingService.queryUser(i);
                String s = DoSomethingService.sendUserEmail(user.getEmail());
                System.out.println(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long singleEnd = System.currentTimeMillis();
        System.out.println("单线程共用了"+(singleEnd-singleStart)+"ms");
        System.out.println("-------分割线-----------------分割线-----------------分割线-----------------分割线-----------------分割线----------");
        long concurrentStart = System.currentTimeMillis();
        //构建要做的任务列表,查询出用户来并且发送邮件
        List tasks = new ArrayList<>();
        for (int i

你可能感兴趣的:(android,java,线程池)