【发布时间】:2018-04-15 00:38:26
【问题描述】:
我目前正在尝试通过使用 10 个线程的 ThreadPool 和仅检查一个线程的第二次运行来检查一个数字是否为素数。这里的想法是,我还检查了使用 10 个线程和 1 个单线程的 ThreadPool 之间的速度差异。
我的问题是,在启动单线程操作之前,我对如何等待 PoolThread 完成有点困惑。
我尝试在我的 PrimeTask 类中同步一个函数,但我对线程还是很陌生,不知道为什么我没有得到想要的行为。我很想知道我缺少什么以及为什么。
import java.util.concurrent.*;
public class PrimeChecker
{
private static ExecutorService executor;
private final static long number = 9223372036854775783L;
private final static int numberOfThreads = 10;
private static long startValues;
private static long endValues;
static long startTime;
static long endTime;
private PrimeChecker() { };
public static void main(String[] args)
{
init();
runThreads();
}
private static void init()
{
startValues = 3L;
endValues = (long) Math.sqrt(number) / 10L;
}
private static void runThreads()
{
startTime = System.currentTimeMillis();
executor = Executors.newFixedThreadPool(numberOfThreads);
System.out.print("Chekcing if " + number + " is a prime number, multithreaded.\n");
for (int x = 1; x < 10; x++)
{
executor.execute(new PrimeTask(number, startValues, endValues));
startValues = ((endValues / 10) * x);
endValues = ((endValues / 10) * (x + 1));
}
executor.shutdown();
singlethreadedPrime();
}
private static void singlethreadedPrime()
{
startTime = System.currentTimeMillis();
executor = Executors.newFixedThreadPool(1);
System.out.println("Chekcing if " + number + " is a prime number, singlethreaded.");
executor.execute(new PrimeTask(number, startValues, endValues));
executor.shutdown();
}
static class PrimeTask implements Runnable
{
private long number;
private long startValue;
private long endValue;
public PrimeTask(long Numb, long startVal, long endVal)
{
number = Numb;
startValue = startVal;
endValue = endVal;
}
@Override
public void run()
{
if (isPrime(number, startValue, endValue))
{
endTime = System.currentTimeMillis();
System.out.printf("Time millisecond: %d\n", (endTime - startTime));
System.out.println(number + " is Prime");
}
else
{
endTime = System.currentTimeMillis();
System.out.printf("Time millisecond: %d\n" + (endTime - startTime));
System.out.println(number + " not Prime");
}
}
public static synchronized boolean isPrime(long n, long sV, long eV)
{
if((n % 2) == 0)
{
return false; // not prime
}
else
{
for(long i = sV; i*i <= eV; i+=2)
{
if(n%i==0)
return false; // not prime
}
return true; // prime
}
}
}
}
【问题讨论】:
-
Executors的工作量完全相同——我的意思是字面意思。为了让您的代码利用多个线程,您实际上需要执行多个任务(每个任务由单个线程执行)。所以在你的runThreads方法中,你需要将你的工作量分解成(可能是 10 个)部分,每个部分计算整体的特定范围(即(endValues - startValues) / 10会给你每个单独任务的整体范围)跨度> -
回答您的问题:像往常一样,您只需阅读 javadoc:docs.oracle.com/javase/8/docs/api/java/util/concurrent/…。这是类中列出的第一个方法!
标签: java multithreading threadpool