java线程池(二)


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ThreadPoolTest {
    static BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>();
    static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,5,3,TimeUnit.SECONDS,workQueue);

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); //拒绝策略
        List<Message> list = new ArrayList<>();
        Future<Boolean>[] futures = new Future[20];
        int i = 0;
        Message msg = new Message("nihao","12346");    
        for(int x=0;x<10;x++) {
            list.add(msg);
        }
        for(Message message : list){
            Future<Boolean> submit = threadPoolExecutor.submit(message);
            futures[i++] = submit;
        }
        //得到返回值,get方法会阻塞线程,所以设置过期时间
        for(Future<Boolean> future : futures){
            if(future == null){
                return;
            }
            System.out.println(future.get(2, TimeUnit.SECONDS));
        }
        
    }


}
class Message implements Callable<Boolean>{

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    String word;
    String target;

    public Message(String word, String target) {
        this.word = word;
        this.target = target;
    }

    @Override
    public Boolean call() throws Exception {
        boolean flag = send(word,target);
        return flag;
    }
    public boolean send(String word,String target){
        System.out.println(word + " " + target);
        return true;
    }
}

只是对代码的分析

    public boolean send(String word,String target){
        System.out.println(word + " " + target);
        return true;
    }

每执行一次进行输出,也就是“nihao 123456”,返回true

        //得到返回值,get方法会阻塞线程,所以设置过期时间
        for(Future<Boolean> future : futures){
            if(future == null){
                return;
            }
            System.out.println(future.get(2, TimeUnit.SECONDS));
        }

这里输出true

        Message msg = new Message("nihao","12346");    
        for(int x=0;x<10;x++) {
            list.add(msg);
        }

这里通过循环创建了10个

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值