码迷,mamicode.com
首页 > 编程语言 > 详细

【多线程实现方案三:实现Callable 接口】

时间:2018-09-03 02:47:15      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:BMI   pool   sub   imp   read   thread   Fix   div   call()   

多线程实现的方式三:

A:创建一个线程池对象,控制要创建几个线程对象。

  public static ExecutorService newFixedThreadPool(int nThreads)

B:做一个类实现Callable接口。

C:调用如下方法即可

  Future<?> submit(Runnable task)

  <T> Future<T> submit(Callable<T> task)

D:我就要结束,可以吗?

  可以。

package com.test;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {

    private int number;

    public MyCallable(int number){
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;

        for(int x=1;x<=number;x++){
            sum +=x;
        }

        return sum;
    }
}
package com.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableTest {

    public static void main(String[] args) throws
            InterruptedException, ExecutionException {

        /**创建线程池对象*/
        ExecutorService pool = Executors.newFixedThreadPool(2);

        /**可以执行Runnable对象或者Callable对象代表的线程*/
        Future<Integer> f1 = pool.submit(new MyCallable(100));
        Future<Integer> f2 = pool.submit(new MyCallable(200));

        /**V get()*/
        Integer i1 = f1.get();
        Integer i2 = f2.get();
        System.out.println(i1);
        System.out.println(i2);

        /**结束*/
        pool.shutdown();

    }

}

运行结果:

5050
20100

 

【多线程实现方案三:实现Callable 接口】

标签:BMI   pool   sub   imp   read   thread   Fix   div   call()   

原文地址:https://www.cnblogs.com/zuixinxian/p/9576490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!