JAVA多线程Callable和Future使用示例

package concurrent;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @Auther:zhouhongliang
 * @Date:2019/7/11
 * @Description:
 * Callable和Future一起使用
 */
public class CallableOne {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future zhangsan = executorService.submit(new MyCalllable("张三"));
        Future lisi = executorService.submit(new MyCalllable("李四"));
        Future wangwu = executorService.submit(new MyCalllable("王五"));
        try {
            //阻塞主线程 get()
            System.out.println(zhangsan.get());
            System.out.println(lisi.get());
            //System.out.println(wangwu.get());
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("主线程执行完毕");
        executorService.shutdown();
    }
}
class MyCalllable implements Callable{
    public MyCalllable(String name) {
        this.name = name;
    }

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        Integer speed = new Random().nextInt(100);
        Integer course = new Integer(0);
        for (int i=1;i<=10;i++){
            course = speed * i;
            System.out.println(name + " 前进了"+course+"米,"+speed+"/秒");
            if ("张三".equals(name)){
                Thread.sleep(100);
            }else{
                Thread.sleep(500);
            }

        }
        return course;
    }
}

新闻标题:JAVA多线程Callable和Future使用示例
当前地址:http://bzwzjz.com/article/pjepoj.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都定制网站建设 成都网站设计 响应式网站建设 重庆网站设计 成都网站制作 成都企业网站设计 手机网站建设套餐 网站设计 成都品牌网站建设 梓潼网站设计 网站设计 专业网站设计 商城网站建设 定制网站设计 成都响应式网站建设 成都网站建设 成都网站建设公司 营销型网站建设 高端网站建设 成都网站设计 响应式网站设计 成都网站建设公司