futureTask

使用多线程来计算 1 到 20万里所有的质数

public class Main {

    //1 -> 20万所有的质数
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        List<Integer> result = getPrime(1,200000);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        final int cpuCore = 3;
        ExecutorService service = Executors.newFixedThreadPool(cpuCore);
        MyTask t1 = new MyTask(1,80000);
        MyTask t2 = new MyTask(80001,110000);
        MyTask t3 = new MyTask(110000,170000);
        MyTask t4 = new MyTask(170001,200000);
        Future<List<Integer>> f1 = service.submit(t1);
        Future<List<Integer>> f2 = service.submit(t2);
        Future<List<Integer>> f3 = service.submit(t3);
        Future<List<Integer>> f4 = service.submit(t4);
        long l = System.currentTimeMillis();
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        System.out.println(System.currentTimeMillis()-l);
        service.shutdown();


    }

    static class MyTask implements Callable<List<Integer>>
    {
        int l, r;
        MyTask(int l,int r)
        {
            this.l = l;
            this.r = r;
        }
        @Override
        public List<Integer> call() throws Exception {
            return getPrime(l,r);
        }
    }

    public static boolean isPrime(int n)
    {
        int tmp = (int)Math.sqrt(n)+1;

        for(int i=2;i<tmp;++i)
        {
            if(n%i==0)
            {
                return false;
            }
        }

        return true;
    }

    static List<Integer> getPrime(int l, int r)
    {
        List<Integer> results = new ArrayList<>(r-l+1);
        for(int i=l;i<=r;++i)
        {
            if(isPrime(i))
            {
                results.add(i);
            }
        }
        return results;
    }








}

在这里插入图片描述

继承 callable接口,实现 call方法,并且包装成 future对象,以开启线程,线程池内开启 3个线程计算

runable 无返回值,callable可以自定义返回值,这是对多线程部分的补充

这里,我指定使用 cpu的核数为 3,

System.out.println(Runtime.getRuntime().availableProcessors());

使用以上方法,即可查看自己电脑的 cpu核数
指定 cpu核数 为 3,启动 3个线程
线程池默认是根据 cpu 是几个核,来启动几条线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值