温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA多线程Callable和Future使用示例

发布时间:2020-06-24 06:53:56 来源:网络 阅读:494 作者:恋上程序员 栏目:编程语言
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;
    }
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI