多线程面试笔试题-1

用多线程求出1到10000之间的素数个数,并输出所有素数?(运行程序的机器是4核处理器)

面试的时候没有写出来,回来之后根据自己的理解编写的,结果是出来了,但是不知道是不是最好,请各位大神点评;

涉及到的知识点:

线程池初始化

线程创建

素数概念

并发包 CountDownLatch 的使用

线程池大小设置参考

因为这里完全是CPU密集型操作,所以线程池的大小为:CPU核数+1 ;

多线程计数器原子性保证方案: AtomicInteger

package com.sysware.cloud.test.controller;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by tianwenqing on 2019/3/5.
 */
public class Test implements Callable {
    private int a ;
    private AtomicInteger count ;
    private CountDownLatch latch ;

    public Test(int a,AtomicInteger count,CountDownLatch latch){
        this.a = a ;
        this.count = count ;
        this.latch = latch ;
    }

    @Override
    public java.util.concurrent.atomic.AtomicInteger call() {
        if(isSuShu(a)){
            System.out.println(Thread.currentThread().getName()+" "+ a);
            count.incrementAndGet();
        }
        latch.countDown();
        return count ;
    }
    public boolean isSuShu(int i){
        boolean flag = true ;
        if(i==1){
            return false ;
        }
        for (int j = 2; j <i ; j++) {
            if(i%j==0){
                return false ;
            }
        }
        return flag ;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CountDownLatch latch = new CountDownLatch(99) ;
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        AtomicInteger count = new AtomicInteger();
        for (int i = 1; i < 100 ; i++) {
            Test test = new Test(i,count,latch);
            executorService.submit(test);
        }
        latch.await();
        System.out.println(count);
        executorService.shutdownNow();
    }

}
原文地址:https://www.cnblogs.com/wenq001/p/10477084.html