Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a thread limit in Java

Let's say I have 1000 files to read and because of some limits, I want to read maximum 5 files in parallel. And, as soon as one of them is finished, I want a new one starts.

I have a main function who have the list of the files and I try changing a counter whenever one thread is finished. but it doesn't works!

Any suggestion?

The following is the main function loop

for (final File filename : folder.listFiles()) {

    Object lock1 = new Object();
    new myThread(filename, lock1).start();
    counter++;
    while (counter > 5);
}
like image 702
Afshin Moazami Avatar asked Dec 28 '11 03:12

Afshin Moazami


People also ask

How do I restrict the number of threads in Java?

Use an ExecutorService and specify the pool to be 5. Put all the files in something like a BlockingQueue or another thread-safe collection and all the executing ones can just poll() it at will.

How many maximum threads can you create?

pid_max value of 131072 above means the kernel can execute a maximum of 131,072 processes simultaneously.

How many threads can run at once?

A single CPU core can have up-to 2 threads per core. For example, if a CPU is dual core (i.e., 2 cores) it will have 4 threads.

How many maximum threads can you run in the 32 bit machine?

The number of threads with the default stack size is approximately 2000 threads on a 32-bit system and 8000 billion on a 64-bit system.


2 Answers

Spawning threads like this is not the way to go. Use an ExecutorService and specify the pool to be 5. Put all the files in something like a BlockingQueue or another thread-safe collection and all the executing ones can just poll() it at will.

public class ThreadReader {

    public static void main(String[] args) {
        File f = null;//folder
        final BlockingQueue<File> queue = new ArrayBlockingQueue<File>(1000);
        for(File kid : f.listFiles()){
            queue.add(kid);
        }

        ExecutorService pool = Executors.newFixedThreadPool(5);

        for(int i = 1; i <= 5; i++){
            Runnable r = new Runnable(){
                public void run() {
                    File workFile = null;
                    while((workFile = queue.poll()) != null){
                        //work on the file.
                    }
                }
            };
            pool.execute(r);
        }
    }
}
like image 179
Kylar Avatar answered Oct 10 '22 10:10

Kylar


You can use an ExecutorService as a thread pool AND a queue.

ExecutorService pool = Executors.newFixedThreadPool(5);
File f = new File(args[0]);

for (final File kid : f.listFiles()) {
    pool.execute(new Runnable() {
        @Override
        public void run() {
            process(kid);
        }
    });
}
pool.shutdown();
// wait for them to finish for up to one minute.
pool.awaitTermination(1, TimeUnit.MINUTES);
like image 32
Peter Lawrey Avatar answered Oct 10 '22 10:10

Peter Lawrey