使用Callable和FutureTask创建多线程

 

public class CallableTest {
    public static void main(String[] args) {
        /**
         * 3.用FutureTask把Callable对象封装成线程任务对象(这是线程一)
         */
        Callable c1 = new MyCallable(100);
        FutureTask<String> future = new FutureTask<>(c1);
        /**
         * 4.把线程任务对象交给Thread处理
         */
        Thread thread1 = new Thread(future);
        /**
         * 调用Thread的start方法启动线程 
         */
        thread1.start();
        /**
         * 这是线程二(同上)
         */
        Callable c2 = new MyCallable(200);
        FutureTask<String> future2 = new FutureTask<>(c2);
        Thread thread2 = new Thread(future2);
        thread2.start();
        try {
            /**
             * 通过FutureTask的get方法  获取结果,并输出(线程一)
             */
            String ture1 = future.get();
            System.out.println("第一个结果: " + ture1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            /**
             * 通过FutureTask的get方法  获取结果,并输出(线程二)
             */
            String ture2 = future2.get();
            System.out.println("第二个结果: " + ture2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 1.继承Callable 要写<>泛型
 * 私有属性 + 有参构造器
 */
class MyCallable implements Callable<String> {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }
    /**
     * 2.重写call()方法
     */
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return "子线程总数为: + " + sum;
    }
}

输出结果:

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值