简体   繁体   中英

Spawning too many threads in java

I just found out what threads are (at least I think I know what they are :s ). I'm programming in java and I created a function that generates Strings. Every time the methode finds a string it calls the update methode and passes the founded string to it. (the stringfinder methode is a recurssive methode).

In the update() methode I want to process that string on another thread . But I don't know how to do this.

At the moment it looks like this

private void update(String input){
new ProcessThread(input).createThreadAndRun();
}

This works. But that isn't how it's done I guess, since the update method is called a few thousand times per second. And every time I create a new thread.

The createThreadAndRun methode looks like this:

@Override
public void createThreadAndRun() {
    Thread thread=new Thread(this,"processThread");
    thread.start();
}

But for the moment it is still spamming ProcessThreads, because every time I find a string , I create a new thread. Does anyone know how this can be fixed? So I only create 1,2 or 3 threads for StringProcessing?

What you want to do is to run your threads on an ExecutorService . Consider the following:

ExecutorService threadpool = Executors.newFixedThreadPool(4);

Then just submit your ProcessThread (which should be called ProcessRunnable or something) with:

threadPool.submit(new ProcessThread(input));

You should use thread pooling. I think this example will give you enough information for your implementation. For more information look at Java docs

With thread poll you achieve this (paraphrasing): "With a limit on the number of the threads that can be created, the application will not be servicing your background jobs (worker threads) as quickly as they come in, but it will be servicing them as quickly as the system can sustain."

You can create fixed thread pool executor like this ExecutorService executor = Executors.newFixedThreadPool(8); and execute worked with something like

executor.submit(worker);

where worker is instance of your job class which implements Runnable or Callable<T>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM