guevarak12
guevarak12

Reputation: 75

Splitting work between threads in a parameter range

I have a method that counts the prime numbers from 1 to x and when x is a really large number like 1000000000, I would like to split the work between threads. My prime counter accepts 1 parameter, x, that is the last number to check whether it is prime or not. This method returns the count, integer of primes in which the method calculated. I know that I can have something like:

Thread thread1 = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            int primes = primeCounter(1000000);
            System.out.println("There are: " + primes+ " primes in betweem 1 and " + 1000000);

        }
    });

But how can I continue from 1000000 to 100000000 with another thread and join those two threads?

Upvotes: 0

Views: 767

Answers (1)

Gren
Gren

Reputation: 1854

First, like mentioned in the comment, change your primecounter so that ist accepts a range. Second, create a class which extends Thread, e.g:

class MyThread extends Thread {
    long start;
    long stop;
    int primes = 0;

    MyThread(long start, long stop) {
        this.start = start;
        this.stop = stop;
    }

    @Override
    public void run() {
        primes = primeCounter(start, stop);
        System.out.println("There are: " + primes + " primes in betweem " + start + " and " + stop);
    }

    private int primeCounter(long start, long stop) {
        int counter = 0;
        //.....
        return counter;
    }
}

Then you can create your threads, starting them and waiting until they are all finished:

    long max = 1000000000;
    long packetSize = 1000000;
    List<MyThread> threads = new ArrayList<>();
    long start = 0;
    for (int i = 0; i < (int) (max / packetSize); i++) {
        threads.add(new MyThread(start, start = start + packetSize));
    }
    threads.forEach((Thread t)-> t.start());
    threads.forEach((Thread t)-> { try {t.join();}catch(InterruptedException e) {throw new RuntimeException(e);}});

The example is very simple, change it to your needs and don't forget the exception handling :)

Upvotes: 1

Related Questions