为什么执行相同行为的线程需要不同的时间?

时间:2013-11-26 05:22:59

标签: java multithreading

我是多线程的新手。我有一个由两个类组成的程序:PrimeNumber和一个主类。我试图找到给定范围内的所有素数。 这是我的PrimeNumber课程:

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;


public class PrimeNumber extends Thread{

    int start, end;
    int threadNumber; //used to display the thread number
    static ArrayList<Integer> list  = new ArrayList<Integer>(1000000);


    public PrimeNumber(int start, int end, int threadNumber) {
        this.start = start;
        this.end = end;
        this.threadNumber = threadNumber;
          // added code
            if(list.isEmpty()){
            list.add(2);
        }


    }
    @Override
    public void run(){
        long startTime = System.nanoTime();
        System.out.println(threadNumber + " started");
        for(int i = start; i<=end;i++){
            if(isPrime(i)){
                list.add(i);
            }

        }
        System.out.println(threadNumber + " has finished");
        long endTime = System.nanoTime();

        System.out.println("Time for thread " + threadNumber + " is " +TimeUnit.SECONDS.convert(endTime-startTime, TimeUnit.NANOSECONDS) + " seconds.");

    }  

//modified method
/**
 *  Determine whether a number is prime 
 * @param number
 * @return true if number is prime, false otherwise
 */


     public boolean isPrime(int number){
        if(number == 0 || number == 1){
            return false;
        }

        else {
            int counter = 0;
            while(counter<list.size()){
                if(number%list.get(counter)==0){
                    return false;
                }
                counter++;
            }
        }

        return true;
    }
  }

这是我的主要课程

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class MainClass {

    public static void main(String[] args) throws InterruptedException{
        final int maxNumberOfThreads = 3; // number of threads I want to create
        final int maxNumber = 900000;   // Max range for which I'm finding all the prime numbers up to it
        int initialNumber = 1;
        ArrayList<Thread> myList = new ArrayList<Thread>();
        for(int i = 0; i < maxNumberOfThreads; i++ ){
            myList.add(new PrimeNumber(initialNumber, initialNumber+ maxNumber/maxNumberOfThreads, i+1));
            myList.get(i).start();
            initialNumber+=maxNumber/maxNumberOfThreads;
        }

        for(Thread thread : myList){

            thread.join();
        }
        try {
            Collections.sort(PrimeNumber.list); // sort the list
            BufferedWriter writer = new BufferedWriter(new FileWriter(new File("Primes.txt"),true));
            for(int i = 0; i <PrimeNumber.list.size(); i++){
                writer.write(PrimeNumber.list.get(i).toString());
                //System.out.println(PrimeNumber.list.get(i));
                writer.newLine();
            }
            writer.close();
            System.out.println("Done writing to the file");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

当我在这里运行我的程序时,我得到了输出:

2 started
3 started
1 started
1 has finished
Time for thread 1 is 3 seconds.
2 has finished
Time for thread 2 is 7 seconds.
3 has finished
Time for thread 3 is 11 seconds.
Done writing to the file

即使线程具有相似的行为(它们都在几乎相同的范围上计算素数),为什么每个线程的执行时间都不同? 我搜索了很长时间但没有找到令人满意的答案。提前谢谢。

编辑:我在isPrime()方法中添加了一个步骤,大大缩短了执行时间。

1 个答案:

答案 0 :(得分:2)

方法中的此循环isPrime在线程3上执行的迭代次数多于在线程2上的迭代次数,并且线程2上的迭代次数多于线程1上的迭代次数,因为在每种情况下测试的数字都不同:

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

此外,三个范围中每个范围的素数不同,因此列表的添加数量也会不同。