Home > front end >  How to make multiple Threads run at the same time using a for loop in Java?
How to make multiple Threads run at the same time using a for loop in Java?

Time:01-08

I'm pretty new to java and started building a small program to find prime numbers in a given range. Now I tried to implement multitasking, e.g. splitting the numbers to be checked into n parts that shall be checked independently. I wanted to make it as flexible as possible, so I didn't specify the number of threads in the code, instead I used a prompt variable. Now, the code works, but the threads don't run parallel.

What seems to be the problem here?

           [...]     
           System.out.println("How many Threads shall be used?");
           int b1 = scan.nextInt();
           scan.close();
           for (int i = 1; i <= b1; i  ) {
             long u = (q/b1)*(i-1);
             long o = (q/b1)*i;
             System.out.println("Thread " i " started.");
             Thread t1 = new Thread(new thread1 (u, o, i));
             t1.start();
           }


class thread1 implements Runnable{
    public thread1 (long a, long b, int c) {
//a= min. number, b = max. number, c=number of Thread
        primefinder.findPrimes(b,a, c);
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
}

CodePudding user response:

From the javadoc https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html :

class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }
    

Your logic must be in the run() method. It's this method that will be called and run on another thread. With your actual code, you do the calculation in the Runnable's constructor, which is called in your for loop, and therefor is sequential.

Moving your calculation to the run method will solve the problem.

edit: if you struggled to pass parameters to your computation code, you could have simplified to this :

Thread t1 = new Thread(() -> findPrimes(u, o, i));
t1.start();

It does exactly the same thing, under the hood, it creates an anonymous class that implement the Runnable interface that captures your variables in the class fields.

CodePudding user response:

As the correct Answer by Daniel says, you need to move your business logic into the run method of a Runnable, or the call method of a Callable to get a value returned via Future.

Also, in modern Java we rarely address the Thread class directly. Instead use the Executors framework.

ExecutorService es = Executors.newFixedThreadPool( x ) ;
for( … ) { es.submit( task ) ; }
es.shutdown() ;
es.awaitTermination( … ) ;

This has been covered many times already on Stack Overflow. So search to learn more.

  •  Tags:  
  • Related