栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java线程池(二)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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 list = new ArrayList<>();
        Future[] 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 submit = threadPoolExecutor.submit(message);
            futures[i++] = submit;
        }
        //得到返回值,get方法会阻塞线程,所以设置过期时间
        for(Future future : futures){
            if(future == null){
                return;
            }
            System.out.println(future.get(2, TimeUnit.SECONDS));
        }
        
    }


}
class Message implements Callable{

    
    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 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个

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/967458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号