J. Doe
J. Doe

Reputation: 65

Should you create an unlimited number of threads in Java?

The program I am writing asks the user for an unlimited number of items and my program will do something with each of those items. I made my program do this over 3 threads, so it will finish faster. With the program I have now it continues to loop through checking if each thread is still running then if 1 of the 3 isn't running it creates a new one. The only reason I create a new one is that it says a thread can only be used once. Is there a better way to do this?

Upvotes: 0

Views: 1327

Answers (2)

Andriy Kryvtsun
Andriy Kryvtsun

Reputation: 3344

Use one of Java concurrency thread pools from Executors factory class and set the number of processors which can be obtained from Runtime.getRuntime().availableProcessors(); as a thread pool size for maximum performance.

Upvotes: 0

Benoit Vanalderweireldt
Benoit Vanalderweireldt

Reputation: 2989

No you shouldn't you should use a ThreadPool, luckily Java already has all you need under the package : java.util.concurrent

Example using a Thread pool with 10 concurrent threads :

import java.io.PrintStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadsExample {

    public static void main(String[] args) throws InterruptedException {

        ExecutorService exec = Executors.newFixedThreadPool(10);
        exec.awaitTermination(1, TimeUnit.SECONDS);
        for (int i = 0; i < 100; i++) {
            exec.submit(new MyTask(System.out));
        }
        exec.shutdown();
    }

    public static class MyTask implements Runnable {
        PrintStream out;
        public MyTask(final PrintStream out) {
            this.out = out;
        }
        public void run() {
            out.println("MyTask executed in : " + Thread.currentThread().getName());
        }
    }

}

Look at java.util.concurrent.Executors class to find other thread pools implementation (scheduled pool, mono thread pool....), also your task could implement the interface Callable, which gives you more control for exception catch and a return object from your thread.

Upvotes: 1

Related Questions